The break statement in MATLAB

The break statement in MATLAB is used to break out of a loop – a for or while statement, that is, it terminates the execution of the loop.  Let’s suppose someone wants to find 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;
end

___________________________________________________________

Let’s suppose now you are asked to calculate value of k^2-50 for all integers in [-10,10] domain but only until k^2-50 becomes negative.

% The loop below will calculate values of k^2-50
% for all values of the requested k
% until it turns negative
for k=-10:1:10
    if (k^2-50<0)
        break;
    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 until it turns negative
k=-10;
while (k<=10) & (k^2-50>0)
    val=k^2-50;
    fprintf(‘\n k=%g  val=%g’,k,val)
    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.

0 thoughts on “The break statement in MATLAB”

Leave a Reply