Professional Documents
Culture Documents
Scilab Programming Looping FOR
Scilab Programming Looping FOR
– FOR loops
Building complex algorithms often requires repetitive actions. For example we need to evaluate the
function f(x) defined below, for different values of x:
f(x)=x2+(√x)
for x = 1, 2, 3, 4, 5
Without knowing that we can use conditional loops to evaluate the function, the only way to evaluate the function, for
every value of x, is to use Scilab console, define x = 1 then evaluate the function, define x = 2 and evaluate the function
and so on.
-->x=1;
f=
2.
-->x=2;
f=
2.
5.4142136
-->x=3;
f=
2.
5.4142136
10.732051
-->x=4;
f=
2.
5.4142136
10.732051
18.
-->x=5;
f=
2.
5.4142136
10.732051
18.
27.236068
-->
In the example above, the function f is a vector and x is function argument and index.
A common conditional loop is the for loop. It’s named conditional because it’s executed depending if a conditions is
true or false. If the condition is true we execute the instruction, if it’s false we stop executing it.
Simple FOR loops
The general syntax of the for loop in Scilab is the following:
Let’s apply the for loop structure to our function (in a Scilab script):
for x=1:1:5
end
In our example x is the index which gets incremented and also the function argument. The first value which is assigned
to x is 1. We evaluate the function f for x=1. After, we increment x with 1 so it becomes 2. We evaluate again the
function for x=2. We do the same operations until x=5.
The results are stored inside a vector f. The first value of f, f(1), corresponds to x=1. The last value of f, f(5),
corresponds to x=5.
If we run this piece of script and display the result of the f function in the console we’ll get:-->f
f=
2.
5.4142136
10.732051
18.
27.236068
-->
Bear in mind that the variable x used in the example above has two roles: as index and argument. We’ll give some
other examples in which there is a distinction between the index and the function argument.
In the image below you can see a logical diagram of the for loop, the events that happen during the loop and the
corresponding Scilab instructions for each event.
This in not efficient at all. By using a for loop the definition of the vector is:
for i=1:100
t_vec(i) = i/10;
end