Decision-Making in MATLAB

 

The inherent potential of programming (in any language) to solve complex engineering problems is realized when decision-making becomes formalized and possible, and when complex operations and calculations can be done repetitively. Coupled with flexible visualization tools these features of MATLAB make it one of the most commonly adopted computational environments for solving engineering design problems. MATLAB has built-in commands and functions for logical operations and conditional branching that make it possible to execute different code segments in different cases. In addition, different commands are available to structure looping operations that execute code segments repetitively either deterministically or coupled to condition statements.

 

Relational Operators and Functions

The usual relational and logical tests associated with mathematical inequality statements (which I’m sure you’ve all seen before) can be accomplished in MATLAB. MATLAB typically executes the required test and returns a true result (1) or false result (0) to a workspace variable. These logical tests can be combined to make fairly complex decisions, and tables of both relational and logical operators are provided on pgs. 249 and 250.  Some simple examples illustrate the idea I think.

» a=2;b=7;

» c=(a==b)

» c=a<b

» c=a>b

» c=(a<d)&(b>d)

» c=(a>b)|(b>d)

These logical operators also accept array arguments and work in much the same way. Thus,

» a=[2 3 5 9];;b=[0 3 7 6];

» c=(a==b)

» c=(a<b)

 

Conditional statements

Conditional statements enable us to write programs that are structured into code segments that are each executed when particular conditions are determined to exist. These conditions are typically formalized, as a logical test on data calculated by MATLAB and execution of the MATLAB code is made conditional on the result of this logical test. This implements what is commonly referred to as branching. The most common way to make this happen is to use the if-elseif statement. An abbreviated copy of the help file is provided in accompanying handout for you. To illustrate how this is used, we’ll write a program to complete problem T6.3-1 on page 263.

 

» help if

 IF statement condition.

    The general form of the IF statement is

 

       IF expression

         statements

       ELSEIF expression

         statements

       ELSE

         statements

       END

    The statements are executed if the real part of the expression has all non-zero elements. The ELSE and ELSEIF parts are optional.  Zero or more ELSEIF parts can be used as well as nested IF's. The expression is usually of the form expr rop expr where rop is ==, <, >, <=, >=, or ~=.

 

    Example

       if I == J

         A(I,J) = 2;

       elseif abs(I-J) == 1

         A(I,J) = -1;

       else

         A(I,J) = 0;

       end

 

    See also RELOP, ELSE, ELSEIF, END, FOR, WHILE, SWITCH.



Example T6.3-1 (Pg. 263). Writing an arcsin function.

·         State the problem concisely.

Given a number x and a quadrant q (q=1,2,3,4), write a program to compute sin-1(x) in degrees, taking into account the quadrant. The program should display an error message if |x|>1.

·         Specify the data to be used by the program. This is the “input”.

x – a real, scalar variable

q – a real, scalar integer

·         Specify the information to be generated by the program. This is the “output”.

th – an angle in degrees

·         Work through the solution steps by hand or with a calculator; use a simpler data set if necessary.

sin(50°)=0.766, sin(-50°)=-0.766, sin(130°)=0.766, sin(-130°)=-0.766

·         Write and run the program.

A pseudocode description:

Given x and q, calculate th=sin-1(x) in degrees.

If |x|>1 print an error message.

Else if q corresponds to the second or third quadrant,

adjust th accordingly and return the result in degrees.

Else if x and q are not in agreement, display an error message.


Looping the Loop in MATLAB

If is fortuitous that MATLAB, like most other computer languages, provides several mechanisms for repetitively executing code segments. We’ve seen already how useful this might prove to be when we need to repeat the same calculation for a variety of different conditions (i.e. in the vibration frequency problem we considered a few weeks ago.) All that remains is to understand and apply the syntax of the different MATLAB commands that enable this type of program structure. There are basically two ways to do this: using a  for loop and using a while loop.

The for loop

The basic syntax for a for loop is provided in the corresponding MATLAB help file. Basically, a loop variable (usually an integer) is established that increments from a defined minimum value to a defined maximum. For each value of the loop variable, a defined code segment is executed. The calculated results for each “pass” through the loop are easily stored in array variables, either as successive columns or successive rows. The calculated data can either be output each time the loop is executed (although this is very time consuming), or can be output or displayed after the loop has terminated.


Example 1:

x=[1:.1:2];

[m,n]=size(x);

for k=1:n

   y(k)=x(k)^2;

end

plot(x,y)

 

Example 2:

sum=0;N=24

for k=1:N

   sum(k+1)=sum(k)+k;

end

stairs(sum)

title(‘Cumulative sum’)

 


The while loop

While loops are used when the termination of a looping process terminates when a particular condition is satisfied. The syntax of the loop is similar to the for loop except that the termination condition is provided in a logical expression associated with the while loop. The help file for the while statement is provided in the handout but a simple example will suffice to illustrate the idea. The example above can be reformulated to use a while statement as:

Example 3:

                        x=1;

                        while (x<=2)

                            y=x^2;

                            x=x+.1;

                        end

The main difference between these two approaches is that it is probably easier to index and save the results in an array if a loop variable such as that in the for  loop, is available.

 

» help for

 

 FOR    Repeat statements a specific number of times.

    The general form of a FOR statement is:

 

       FOR variable = expr, statement, ..., statement END

 

    The columns of the expression are stored one at a time in the variable and then the following statements, up to the END, are executed. The expression is often of the form X:Y, in which case its columns are simply scalars. Some examples (assume N has already been assigned a value).

 

         FOR I = 1:N,

             FOR J = 1:N,

                 A(I,J) = 1/(I+J-1);

             END

         END

 

    FOR S = 1.0: -0.1: 0.0, END steps S with increments of -0.1

    FOR E = EYE(N), ... END  sets E to the unit N-vectors.

 

    Long loops are more memory efficient when the colon expression appears in the FOR statement since the index vector is never created.

 

    The BREAK statement can be used to terminate the loop prematurely.

 

    See also IF, WHILE, SWITCH, BREAK, END.


» help while

 

 WHILE  Repeat statements an indefinite number of times.

    The general form of a WHILE statement is:

 

       WHILE expression

         statements

       END 

 

    The statements are executed while the real part of the expression has all non-zero elements. The expression is usually the result of expr rop expr where rop is ==, <, >, <=, >=, or ~=.

 

    The BREAK statement can be used to terminate the loop prematurely.

 

    For example (assuming A already defined):

 

            E = 0*A; F = E + eye(size(E)); N = 1;

            while norm(E+F-E,1) > 0,

               E = E + F;

               F = A*F/N;

               N = N + 1;

            end

 

    See also FOR, IF, SWITCH, BREAK, END.

 

»

 

 

This page was created by Dr. Malcolm Daniels of the Department of Electrical and Computer Engineering.