This course will become read-only in the near future. Tell us at community.p2pu.org if that is a problem.

Session 9: Scilab Programming Language [June 8, 2011, 12:19 p.m.]


During our interaction with Scilab, we have been using the Scilab programming language even though we have been thinking we are using Scilab commands and not the programming language. That is because, we have not interactively used any program flow control structures such as if(), for etc. Nevertheless, we already know a little bit about Scilab programming language, such as, creating variables, writing expressions and statements, calling functions. Th eadditional things we need to learn are:

  1. Program flow control structures.
  2. Boolean operations, expressions and statements.
  3. Writing our own functions and using them within Scilab
  4. File input and output

Program Flow Control - Loops

The for Loop

Let us display the numbers from 1 to 5 using the for loop:

-->for i = 1:5
-->disp(i)
-->end
  1.
  2.
  3.
  4.
  5.

Let us display all odd numbers between 1 and 5:

-->for i = 1:2:5
-->disp(i)
-->end
  1.
  3.
  5.

The values of the loop index variable i are the values of the range used to define loop. Hence the increment can be a fraction, or it can be negative.

The while Loop

Let us calculate the machine epsilon using the while loop:

-->e = 1; k = 0;
-->while 1+(e/2) ~= 1 do
-->e = e / 2; k = k + 1;
-->end
-->e, k
 e  =
    2.200D-16
 k  =
    52.

Starting from e = 1, it takes 52 iterations to arrive at the machine epsilon, namely, 2.200D-16.

The do in the while loop after the expression 1+(e/2) ~= 1 can be replaced with then, or alternately, it can also be completely dropped.

Program Flow - Branching and Decision Making

Branching using if-then-elseif-else

The following code segment shows how to use the if-then-elseif-else control structure:

-->x = int(rand(1) * 100 - 50);
-->if x > 0 then
-->disp('Positive')
-->elseif x == 0 then
-->disp('Zero')
-->else
-->disp('Negative')
-->end

Output of the above statements is one of Positive, Zero or Negative depending on the value of x. You will also notice that when you type the above statements interactively, the result will be displayed even before the closing end is typed. This is due to the short circuiting of boolean expression evaluation - when one of the conditions being tested is met, there is no need to evaluate the remaining tests.

Branching using select

 

Boolean Operations, Expressions and Statements