Scilab Home page | Wiki | Bug tracker | Forge | Mailing list archives | ATOMS | File exchange
Please login or create an account
Change language to: Français - Português - 日本語 - Русский
Scilab Help >> Scilab > Control flow > for

for

keyword entering a non-conditional loop

Description

Used to define loops. Its syntax is: for variable=expression ,instruction, .. ,instruction,end

for variable=expression do instruction, ,instruction,end

If expression is a matrix or a row vector, variable takes as values the values of each column of the matrix.

A particular case uses the colon operator to create regularly spaced row vectors, and is similar to traditional for loop forms: for variable=n1:step:n2, ...,end

If expression is a list variable takes as values the successive entries of the list.

According to the Code Conventions for the Scilab Programming Language it is recommended:

  • Start each statement on a new line.

  • Write no more than one simple statement per line.

  • Break compound statements over multiple lines.

For example, use:

for i = 1:5
    disp(i);
end
rather than
for i = 1:5, disp(i); end
The number of characters used to define the body of any loop or conditional instruction (if while for or select/case) must be limited to 16 kB.

Examples

Common loops:

n=5;
for i = 1:n
    for j = 1:n
        a(i,j) = 1/(i+j-1);
    end;
end
for j = 2:n-1
    a(j,j) = j;
end;
a

"Decreasing" loop:

for j = 4:-1:1
    j
end

Loop implicitly on the columns of a row vector or of a matrix:

M = [1 2 ; 3 4 ; 5 6]'
for  c = M, c, end
-> M = [1 2 ; 3 4 ; 5 6]'
 M  =
   1.   3.   5.
   2.   4.   6.

--> for  c = M, c, end
 c  =
   1.
   2.

 c  =
   3.
   4.

 c  =
   5.
   6.
for v = a, write(%io(2),v), end
for j = 1:n, v = a(:,j), write(%io(2),v), end

Loop on entries of a list:

for l = list([1 2;3 4], (1+%z)^3, 'example', [%F %T]); l, end
--> for l = list([1 2;3 4], (1+%z)^3, 'example', [%F %T]); l, end
 l  =
   1.   2.
   3.   4.

 l  =
            2   3
   1 +3z +3z  +z

 l  =
 example

 l  =
  F T

See also

  • while — while keyword
  • end — end keyword
  • do — language keyword for loops

History

VersionDescription
6.0.0 The for expression can now be a vector of graphic handles. for is now protected: Assignments like for=1 are no longer possible.
Scilab Enterprises
Copyright (c) 2011-2017 (Scilab Enterprises)
Copyright (c) 1989-2012 (INRIA)
Copyright (c) 1989-2007 (ENPC)
with contributors
Last updated:
Thu Feb 14 14:57:05 CET 2019