For in Scilab
In Scilab, loops can be constructed using various methods. Here are some basic types of loops equivalent to the original example.
// The most basic type, with a single condition.
i = 1;
while i <= 3
disp(i)
i = i + 1;
end
// A classic initial/condition/after loop.
for j = 1:3
disp(j)
end
// Another way of accomplishing the basic "do this N times" iteration.
for i = 1:3
disp(['range ', string(i-1)])
end
// Loop without a condition will continue until a break or return.
while %T
disp('loop')
break
end
// You can also continue to the next iteration of the loop.
for n = 1:6
if modulo(n-1, 2) == 0 then
continue
end
disp(n-1)
endTo run this Scilab script, save it to a file (e.g., for_example.sce) and execute it in Scilab:
--> exec('for_example.sce', -1)
1.
2.
3.
1.
2.
3.
range 0
range 1
range 2
loop
1.
3.
5.Let’s break down the differences and similarities:
Scilab uses
whilefor condition-based loops, similar to the first example in the original code.The classic
forloop in Scilab uses a different syntax. Instead of specifying initialization, condition, and increment separately, Scilab uses a range (1:3means from 1 to 3).Scilab doesn’t have a direct equivalent to the
rangefunction over integers. We simulate this by using a regularforloop and adjusting the output.An infinite loop in Scilab is created using
while %T(%T represents true).Scilab supports
breakandcontinuestatements similar to other languages.Scilab’s indexing starts at 1, not 0, so we adjust our calculations and output accordingly.
Scilab uses
disp()function for output instead ofprintorprintln.
These examples demonstrate various looping constructs in Scilab, covering most common use cases for iteration.