Control Flow - MATLAB & Simulink
-
Upload
shaukat-ali-shah -
Category
Documents
-
view
233 -
download
0
Transcript of Control Flow - MATLAB & Simulink
-
7/27/2019 Control Flow - MATLAB & Simulink
1/4
Uni ted S tate s Con tact Us S tore
Create Account Log
Products & Services Solutions Academia Support User Community Events Company
Trial Sof tw are Product Updates SharDocumentation Center
Search R2013b Documentation
MATLAB
Control Flow
On this page
Conditional Control if, else, sw itch
Loop Con trol for, while, continue, break
Program Termination return
Vectorization
Preallocation
Conditional Control if, else, switchConditional s tatements enable you to select at run time which block of code to execute. The sim plest conditional statement is an if
statement. For example :
% Generate a random number
a = randi(100, 1);
% If it is even, divide by 2
if rem(a, 2) == 0
disp('a is even')
b = a/2;
end
if statements can include alternate choices, using the op tional keywords elseif orelse. For example:
a = randi(100, 1);
if a < 30
disp('small')
elseif a < 80
disp('medium')
else
disp('large')
end
Alternatively, when you want to test for equa lity agains t a set of known values, us e a switch statement. For example:
[dayNum, dayString] = weekday(date, 'long', 'en_US');
switch dayString
case 'Monday'
disp('Start of the work week')
case 'Tuesday'
disp('Day 2')case 'Wednesday'
disp('Day 3')
case 'Thursday'
disp('Day 4')
case 'Friday'
disp('Last day of the work week')
otherwise
disp('Weekend!')
end
For both if and switch, MATLAB executes the code corresponding to the first true condition, and then exits the code b lock. Each
conditional statement requires the end keyword.
In general, when you have many poss ible dis crete, known values, switch statements are easier to read than if statements. However, you
cannot test for inequa lity between switch and case values . For example , you cannot im plement this type of condition with a switch:
Accel erati ng th e pace of en gin eeri ng an d sci ence
http://www.mathworks.com/help/matlab/learn_matlab/flow-control.html#brbss8u-1http://www.mathworks.com/help/matlab/learn_matlab/flow-control.html#brbss8ahttp://www.mathworks.com/support/http://www.mathworks.com/matlabcentral/http://www.mathworks.com/company/events/http://www.mathworks.com/help/matlab/ref/switch.htmlhttp://www.mathworks.com/help/matlab/ref/if.htmlhttp://www.mathworks.com/help/matlab/learn_matlab/flow-control.html#f4-24700http://www.mathworks.com/help/matlab/learn_matlab/flow-control.html#f4-24622http://www.mathworks.com/help/matlab/learn_matlab/flow-control.html#brbss9a-1http://www.mathworks.com/help/matlab/learn_matlab/flow-control.html#brbss8u-1http://www.mathworks.com/help/matlab/learn_matlab/flow-control.html#brbss8ahttp://www.mathworks.com/help/matlab/index.htmlhttp://www.mathworks.com/help/documentation-center.htmlhttp://www.addthis.com/bookmark.php?v=250&pubid=mathworkshttp://www.mathworks.com/support/web_downloads_bounce.html?s_cid=1008_degr_docdn_270055http://www.mathworks.com/programs/bounce/doc_tryit.htmlhttp://www.mathworks.com/company/http://www.mathworks.com/company/events/http://www.mathworks.com/matlabcentral/http://www.mathworks.com/support/http://www.mathworks.com/academia/http://www.mathworks.com/solutions/http://www.mathworks.com/products/https://www.mathworks.com/accesslogin/login.do?uri=http://www.mathworks.com/help/matlab/learn_matlab/flow-control.html%3Fs_tid%3Ddoc_12bhttps://www.mathworks.com/accesslogin/createProfile.do?uri=http://www.mathworks.com/help/matlab/learn_matlab/flow-control.html%3Fs_tid%3Ddoc_12bhttp://www.mathworks.com/store/default.do?s_cid=store_top_navhttp://www.mathworks.com/company/aboutus/contact_us/http://www.mathworks.com/company/worldwide/ -
7/27/2019 Control Flow - MATLAB & Simulink
2/4
yourNumber = input('Enter a number: ');
if yourNumber < 0
disp('Negative')
elseif yourNumber > 0
disp('Positive')
else
disp('Zero')
end
Array Comparisons in Conditional Statements
It is important to understand how relational operators and if statements work with ma trices. When you want to check for equality between
two variables , you might use
if A == B, ...
This i s valid MATLAB code, and does what you expect when A and B are scalars. But when A and B are matrices, A == B does not test if
they are equal, it tests where they are equal ; the result is another matrix of 0s and 1s showing elem ent-by-elemen t equality. (In fact, ifA and
B are not the same s ize, then A == B is an e rror.)
A = magic(4); B = A; B(1,1) = 0;
A == B
ans =
0 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
The proper way to check for equality between two variables is to us e the isequal function:
if isequal(A, B), ...
isequal returns a scalarlogical value of1 (representing true) or0 (false), instead of a m atrix, as the expression to be evaluated by the
if function. Using the A and Bmatrices from above, you get
isequal(A, B)
ans =
0
Here is another example to em phasize this point. IfA and B are scalars , the following program will never reach the "unexpected situation".
But for most pairs of matrices, including our magic squares with interchanged columns, none of the matrix conditions A > B, A < B, orA
== B is true forallelements and so the else clause is executed:
if A > B
'greater'
elseif A < B
'less'elseif A == B
'equal'
else
error('Unexpected situation')
end
Several functions are helpful for reducing the resu lts of matrix comparis ons to scala r conditions for use with if, including
isequal
isempty
all
any
Loop Control for, while, continue, break
This s ection covers thos e MATLAB functions that provide control over program loops.
forThe for loop repeats a g roup of statements a fixed, predetermined number of times. A matching end delineates the statements:
for n = 3:32
r(n) = rank(magic(n));
end
r
The semicolon terminating the inner statement suppresses repeated printing, and the r after the loop di splays the final result.
It is a good idea to indent the loops for readabili ty, especially when they are nested:
for i = 1:m
for j = 1:n
H(i,j) = 1/(i+j);
end
end
http://www.mathworks.com/help/matlab/ref/end.htmlhttp://www.mathworks.com/help/matlab/ref/for.htmlhttp://www.mathworks.com/help/matlab/ref/isequal.html -
7/27/2019 Control Flow - MATLAB & Simulink
3/4
while
The while loop repeats a group of statements an i ndefinite number of times under control of a logical condition. A matching end
delineates the statements.
Here is a complete program, illustrating while, if, else, and end, that uses in terval bis ection to find a zero of a polynomia l:
a = 0; fa = -Inf;
b = 3; fb = Inf;
while b-a > eps*b
x = (a+b)/2;
fx = x^3-2*x-5;
if sign(fx) == sign(fa)
a = x; fa = fx;
elseb = x; fb = fx;
end
end
x
The result is a root of the polynomialx3 - 2x- 5, namely
x =
2.09455148154233
The cautions involving matrix comparisons that are discuss ed in the section on the if statement als o apply to the while statement.
continue
The continue statement pas ses control to the next iteration of the for loop orwhile loop in which it appears, skipping any remaining
statements i n the body of the loop. The same holds true forcontinue statements in nested loops. That is, execution continues at the
beginning of the loop in which the continue statement was encountered.
The example below s hows a continue loop that counts the lines of code in the file magic.m, skipping all blank lines and comments. A
continue statement is used to advance to the next line in magic.mwithout incrementing the count whenever a blank line or comm ent line
is encountered:
fid = fopen('magic.m','r');
count = 0;
while ~feof(fid)
line = fgetl(fid);
if isempty(line) || strncmp(line,'%',1) || ~ischar(line)
continue
end
count = count + 1;
end
fprintf('%d lines\n',count);
fclose(fid);
breakThe break statement lets you exit early from a for loop orwhile loop. In nested loops, break exits from the innerm ost loop only.
Here is an improvement on the example from the previous section. Why is this use ofbreak a good idea?
a = 0; fa = -Inf;
b = 3; fb = Inf;
while b-a > eps*b
x = (a+b)/2;
fx = x^3-2*x-5;
if fx == 0
break
elseif sign(fx) == sign(fa)
a = x; fa = fx;
else
b = x; fb = fx;
endend
x
Program Termination return
This section covers the MATLAB return function that enables you to terminate your program before it runs to completion.
return
return terminates the current sequence of comm ands and returns control to the invoking function or to the keyboard. return is also used
to terminate keyboardmode. A called function normal ly transfers control to the function that invoked it when i t reaches the end of the
function. You can insert a return statement within the called function to force an early termination and to transfer control to the invoking
function.
Vectorization
One way to make your MATLAB programs run faster is to vectorize the algorithms you use in constructing the program s. Where other
programming languages might use for loops orDO loops, MATLAB can use vector or ma trix operations. A s imple example involves
http://www.mathworks.com/help/matlab/ref/return.htmlhttp://www.mathworks.com/help/matlab/ref/break.htmlhttp://www.mathworks.com/help/matlab/ref/continue.htmlhttp://www.mathworks.com/help/matlab/ref/end.htmlhttp://www.mathworks.com/help/matlab/ref/while.html -
7/27/2019 Control Flow - MATLAB & Simulink
4/4
creating a table of logarithms:
x = .01;
for k = 1:1001
y(k) = log10(x);
x = x + .01;
end
A vectorized version of the same code is
x = .01:.01:10;
y = log10(x);
For more comp licated code, vectorization options are not always so obvious.
Preallocation
If you cannot vectorize a piece of code, you can make yourfor loops go faster by preallocating any vectors or arrays in which output resul ts
are stored. For example , this code uses the function zeros to preallocate the vector created in the for loop. This makes the for loop
execute signi ficantly faster:
r = zeros(32,1);
for n = 1:32
r(n) = rank(magic(n));
end
Without the preallocation in the previous example, the MATLAB interpreter enlarges the r vector by one element each time through the loop.
Vector preallocation eliminates this s tep and results in faster execution.
Was this topic helpful? Yes No
Try MATLAB, Simulink, and Other Products
Get trial now
Join the conversat
Preventing PiracyPrivacy PolicyTrademarksPatentsSite Help 1994-2013 T he M athWorks, Inc.
http://www.mathworks.com/help.htmlhttp://www.mathworks.com/company/aboutus/policies_statements/patents.htmlhttp://www.mathworks.com/company/aboutus/policies_statements/trademarks.htmlhttp://www.mathworks.com/company/aboutus/policies_statements/http://www.mathworks.com/company/aboutus/policies_statements/piracy.htmlhttp://www.mathworks.com/programs/bounce_hub_generic.html?s_tid=mlc_twt&url=http://www.twitter.com/MATLABhttp://www.mathworks.com/programs/bounce_hub_generic.html?s_tid=mlc_fbk&url=http://www.facebook.com/MATLABhttp://www.mathworks.com/programs/bounce_hub_generic.html?s_tid=mlc_glg&url=https://plus.google.com/117177960465154322866?prsrc=3http://www.mathworks.com/programs/bounce_hub_generic.html?s_tid=mlc_lkd&url=http://www.linkedin.com/company/the-mathworks_2http://www.mathworks.com/company/rss/index.htmlhttp://www.mathworks.com/programs/trials/trial_request.html?prodcode=ML&eventid=711257130&s_iid=doc_trial_ML_footer