• No results found

MATLAB Fundamentals

2.6    MATLAB Program Flow

An existing data file can also be entered into a program by the load com-mand. The load command, unlike the fscanf command, leaves rows as rows and columns as columns.

For example:

load filename.txt

x = filename(:,1);

y = filename(:,2);

The input file must have the same number of rows in each column.

2.6   MATLAB Program Flow

The for loop provides the means to carry out a series of statements with just a few lines of code.

Syntax:

for m = 1:20 statement;

statement; ⋮

end

MATLAB sets the index m to 1, carries out the statements between the for and end statements, then returns to the top of the loop, changes m to 2, and repeats the process. After the 20th iteration, the program exits the loop. Any statement that is not to be repeated should not be within the for loop. For example, table headings that are not to be repeated should be outside the for loop.

Example (write this simple program in the Script window, save it as for_

loop_example.m, and run the script):

% for_loop_example.m

clear; clc;

% Table headings:

fprintf(' n y1 y2 \n');

fprintf(' ---\n');

% Using the index in the for loop in an arithmetic statement

for j = 1:10

y1 = j^2/10;

y2 = j^3/100;

fprintf('%5i %10.3f %10.3f \n',j,y1,y2);

end

Note: If the index in a for loop is used to select an element of a matrix, then the index must be an integer. However, if you are not using the for index as a matrix index, then the for index need not be an integer as shown in the following example (write this simple program in the Script window, save it as for_loop_example2.m, and run the script):

% for_loop_example2.m

% Using a range of non-integer x values in a for loop.

% The range of x is from -0.9 to +0.9 in steps of 0.1.

clear; clc;

% print the table header outside of the 'for' loop:

fprintf(' x y1 y2 \n');

fprintf(' ---\n');

for x = -0.9:0.1:0.9

y1 = x/(1-x);

y2 = y1^2;

fprintf('%5.2f %10.3f %10.3f \n',x,y1,y2);

end

The while loop Syntax:

n = 0;

while n < 10

n = n+1;

statement;

statement;

end

In the while loop, MATLAB will carry out the statements between the while and end statements as long as the condition in the while statement is satisfied. If an index in the program is required, the use of the while loop statement (unlike the for loop) requires that the program create its own index, as shown above. Note that the statement “n=n+1” may not make sense alge-braically but does makes sense in the MATLAB language. The “=” operator in MATLAB (as in many computer languages) is the assignment operator, which tells MATLAB to fetch the contents of the memory cell containing the variable n, put its value into the arithmetic unit of the CPU (central processing unit), increment by 1, and put the new value back into the memory cell designated for the variable n. Thus, the old value of n has been replaced by the new value for n.

◾ if statement Syntax:

if logical expression

statement;

⋮ statement;

else

statement;

statement;

end

If the logical expression is true, then only the upper set of statements is executed. If the logical expression is false, then only the bottom set of state-ments is executed.

◾ Logical expressions are of the form

a == b; a <= b;

a < b; a >= b;

a > b; a ~= b; (a not equal to b)

◾ Compound logical expressions

a > b && a ~= c (a > b AND a ≠ c) a > b || a < c (a > b OR a < c)

◾ The if-elseif ladder Syntax:

if logical expression 1 statement(s);

elseif logical expression 2 statements(s);

elseif logical expression 3 statement(s);

else

statement(s);

end

The if-elseif ladder works from top down. If the top logical expression is true, the statements related to that logical expression are executed, and the pro-gram will leave the ladder. If the top logical expression is not true, the program moves to the next logical expression. If that logical expression is true, the program will execute the group of statements associated with that logical expression and leave the ladder. If that logical expression is not true, the program moves to the next logical expression and continues the process. If none of the logical expres-sions are true, the program will execute the statements associated with the else

statement. The else statement is not required. In that case, if none of the logical expressions are true, no statements within the ladder will be executed.

◾ The break command may be used within a for or while loop to end the loop; for example:

for m = 1:20 statement;

statement;

if m > 10 break;

end end

In this example, when m becomes greater than 10, the program leaves the for loop and moves on to the next statement in the program.

◾ The switch group Syntax:

switch(var) case var1

statement(s);

case var2 statement(s);

case var3 statement(s);

otherwise statement(s);

end

where var takes on the possible values var1, var2, var3, and so on.

If var equals var1, those statements associated with var1 are executed, and the program leaves the switch group. If var does not equal var1, the pro-gram tests if var equals var2, and if yes, the program executes those statements associated with var2 and leaves the switch group. If var does not equal any of var1, var2, and so on, the program executes the statements associated with the otherwise statement. If var1, var2, and so on are strings, they need to be enclosed by single quotation marks. It should be noted that var cannot be a logi-cal expression, such as var1 >= 80. For example (write this simple program in the Script window, save it as switch_example.m, and run the program):

% switch_example.m

% This program is a test of the switch statement.

clear; clc;

var = 'a';

x = 5;

switch(var)

case 'b'

z = x^2;

case 'a'

z = x^3;

end

fprintf('z = %6.1f \n',z);

Additional example programs follow that demonstrate the use of the for loop, nested for loops, the while loop, the if statement, the if-elseif statements, the break statement, the input statement, and the fprintf statement. Since a number of these sample programs involve determining ex by a Taylor series expansion, we start with a discussion of the series expansion of ex.

Example 2.1:  Calculation of ex

The Taylor series expansion of ex to n terms is



There are several possible programming algorithms to calculate this series.

The simplest method is to start with sum = 1 and then evaluate each term using exponentiation and MATLAB’s factorial function and add the obtained term to sum. An alternative approach would be to evaluate each term individually, save them in an array, and then use MATLAB’s sum function to add them all.

However, for some series expressions it is best to compute each term in the series based on the value of the preceding term. For example, in the above series, we can see that the third term in the series can be obtained from second term by multiplying the second term by x and dividing by 3; that is, term3 = term2 ⋅ x/3. In general, term (n) = term(n–1) ⋅ x/n.

if(abs(term) <= s*1.0e-7)

---Example 2.2:  Nested Loops

% Example_2_2.m

---Note: In this example, the two statements for i = 1:11

x = xmin+(i-1)*dx;

could be replaced with the following single statement:

for x = -0.5:0.1:0.5

This approach is acceptable when the for loop index is not used to select an element of a matrix. In MATLAB, the variable selecting an element of a matrix must be an integer.

Example 2.3:  While Loop

% Example_2_3.m

% Calculation of e^x by both MATLAB's exp function and

% the Taylor series expansion of e^x. The input()

% function is used to establish the exponent x.

% A 'while' loop is used in determining the series

% solution. A 'break' statement is used to end the loop

% if the number of terms becomes greater than 50. The

% display statement is used to display the values of x,

% ex and ex2 in the command window.

% Note: e^x = 1 + x + x^2/2! + x^3/3! + x^4/4! + ...

clear; clc;

x=input('Enter a value for the exponent x \n');

n=1; ex=1.0; term=1.0;

while abs(term) > ex*1.0e-6 term=x^n/factorial(n);

ex=ex+term;

n=n+1;

if n > 50 break;

end end

ex2=exp(x);

disp(x);

disp(ex);