The continue statement in MATLAB is used to pass control to the next iteration in for and while statements. Let’s suppose someone wants to find and print the value of k^2-50 for all integers in [-10,10] domain. The mfile for that is given below.
% For integers k=-10,-9,….,9,10,
% the function k^2-50 will take positive as
% well as negative values.
%For example, for k=-9, k^2-50=31; for k=1,
% k^2-50=-49; for k=8, k^2-50=14.
% The loop below will calculate values of k^2-50 for
% all values of requested k.
for k=-10:1:10
val=k^2-50;
fprintf(‘\n k=%g val=%g’,k,val)
end
___________________________________________________________
Let’s suppose now you are asked to calculate and print value of k^2-50 for all integers in [-10,10] domain but only if (k^2-50) is positive.
% The loop below will calculate and print values of k^2-50
% for all values of the requested k
% for which k^2-50 is positive.
for k=-10:1:10
if (k^2-50<0)
continue;
end
val=k^2-50;
fprintf(‘\n k=%g val=%g’,k,val)
end
____________________________________________________________
Can you do what you did above using the while statement. Yes, the MATLAB code is given below.
% Equivalent in while
% The loop below will calculate values of k^2-50
% for all values of the requested k for which k^2-50 is positive.
k=-10;
while (k<=10)
if (k^2-50>0)
val=k^2-50;
fprintf(‘\n k=%g val=%g’,k,val)
end
k=k+1;
end
_______________________________________________________
This post is brought to you by Holistic Numerical Methods: Numerical Methods for the STEM undergraduate at http://nm.mathforcollege.com, the textbook on Numerical Methods with Applications available from the lulu storefront, and the YouTube video lectures available at http://nm.mathforcollege.com/videos and http://www.youtube.com/numericalmethodsguy
Subscribe to the blog via a reader or email to stay updated with this blog. Let the information follow you.