0% found this document useful (0 votes)
29 views16 pages

Matlab Tutor6 Break Continue

Uploaded by

Gemini Goel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views16 pages

Matlab Tutor6 Break Continue

Uploaded by

Gemini Goel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

MATLAB break

The break statement terminate the execution of a for loop or while loop. When a break
statement is encountered, execution proceeds with the next statement outside of the
loop. In nested loops, break exists from the innermost loop only.

Syntax:

1. break

Following are the points while using a break statement in


MATLAB:
ADVERTISEMENT

o The break keyword is used to define a break statement.


o The break statement terminates or stops the execution of the for or while loop
and statements those coming after the break statement do not execute.
o After the execution of the break statement, then control passes to the statement
that follows the end of the loop.
o If the break statement occurs in a nested loop, then it terminates only that
particular loop, not the outer loop, and control passes to the statement that
follows the end of that loop.
o The break statement only affects the execution of the for or while loop; hence, it
doesn't define outside the for or while

Flowdiagram of Break Statement


Example1:

1. % program to break the flow at a specified point


2.
3. a = randi(100,6,6)
4. k = 1;
5. while k
6. disp('program running smoothly')
7. if a(k) == 27
8. disp('program encounters the number 27, which is not useful for the current progra
m;')
9. disp(['at index no.:',num2str(k)])
10. disp('so loop terminates now.....bye bye')
11. break
12. end
13. k = k+1;
14. end

Output:

a = 6×6
82 17 70 54 54 10
27 18 70 66 33 27
60 43 64 41 11 16
3 10 4 82 62 29
43 60 7 72 78 45
32 48 32 97 43 53
program running smoothly
program running smoothly
program encounters the number 27, which is not useful for the current
program;
at index no.:2
so loop terminates now.....bye bye

Example2:

1. % program to terminate the execution on finding negative input


2. a = randn(4)
3. k = 1;
4. while k < numel(a)
5. if a(k) < 0
6. break
7. end
8. k = k + 1;
9. end
10. disp(['negative number :', num2str(a(k)), ',found at index: ', num2str(k),',hence the progra
m terminated'])

Output:

Output:

a = 4×4
0.2398 -1.6118 0.8617 0.5812
-0.6904 -0.0245 0.0012 -2.1924
-0.6516 -1.9488 -0.0708 -2.3193
1.1921 1.0205 -2.4863 0.0799
negative number :-0.69036,found at index: 2,hence the program terminated

Program to terminate the flow of execution using the break statement.

Example:

Suppose we have a system that running on temperature variance. The temperature of


the environment defines the working of the system. If the temperature of the
environment passes beyond the hazardous limit, the program must stop the execution
of the application that running the system.

The working temperature range varies according to some predefined conditions. So


during summertime, when heat waves can damage the sophisticated system, or there is
a drop in temperature below the specified limit during winter, we need to protect the
system from getting it down.

The temperature range varies from -100° c to + 600°c.

The system is installed at different locations all over the world. Somewhere the
temperature is measured in Celsius and somewhere it is measured in Fahrenheit. So we
need to take care of these temperature units also.

1. need to take care of these temperature units also.


2. % Program to break the flow of Execution
3. u = symunit; % symunit returns symbolic unit
4. f = randi(200,4,4) % assume this function returns temperature in Fahrenheit
5. tf = {f,u.Fahrenheit}; % create cell array by adding Fahrenheit unit
6. tc = unitConvert(tf,u.Celsius,'Temperature','absolute'); % conversion to Celsius
7. vpan = vpa(tc,3) % conversion from equation to decimal form
8. min_t = -10; % minimum temperature
9. max_t = +60; % maximum temperature
10. tcd = double(separateUnits(vpan)); % convert to double by separating unit symbol
11. for k = 1:16
12. if (tcd(k) <= min_t)
13. disp(['application stopped, temperature dropped below the limit of -
10 & current temp is : ',num2str(tcd(k)),'degree'])
14. break
15. else
16. if (tcd(k) >= max_t)
17. disp(['application stopped, temperature exceeds limit of +60 & current temp is : '
,num2str(tcd(k)),'degree'])
18. break
19. end
20. end
21. end

The continue statement works within a for or while loop and passes control to the next
iteration of the loop.

Syntax:

1. Continue

Following are the points while using a continue statement in MATLAB:

o Continue statement passes the control of the execution to the next iteration of
a for or while loop.
o All remaining statements following the continue statement do not execute for the
current iteration.
o The continue statement applies only to the body of the loop where it is called, hence in
nested loops, it affects the execution of the loop in which it occurs.
o The continue statement only works inside a for or while loop, and it can't be used inside
a function. But if a function is having a for or while loop, there we can
use continue inside the loop.
Flowdiagram of Continue Statement

Example1:
1. % program to print all numbers divisible by 3 and skip remaining
2. a = (1:4:50); % creates row vector from 1 to 50 with a step of 4
3. for k = 1:numel(a)
4. if rem(a(k),3)
5. continue
6. end
7. disp(a(k))
8. end

Output:

21

33

45

continue with nested if-else


Example:
1. % program to find number which is divisible by all numbers from 2 to 9
2. v = [2,3,4,5,6,7,8,9];
3. min = 1;
4. max = 10000;
5. for m = min : max
6. if mod(m,v(1))
7. continue
8. else
9. if mod(m,v(2))
10.
11. continue
12. else
13. if mod(m,v(3))
14. continue
15. else
16. if mod(m,v(4))
17. continue
18. else
19. if mod(m,v(5))
20. continue
21. else
22. if mod(m,v(6))
23. continue
24. else
25. if mod(m,v(7))
26. continue
27. else
28. if mod(m,v(8))
29. continue
30. else
31. disp(['divisible by all :' num2str(m)])
32.
33. end
34. end
35. end
36. end
37. end
38.
39. end
40. end
41. end
42.
43. end
44. disp('....')

MATLAB Error Control Statement-try, catch


MATLAB define some functions that are used to control error. The try-catch statement is
an error control function, which is explained below.

Try - catch statement


Try-catch statement provides error handling control. General form of the try-catch
statement is

Syntax:

1. try
2. Statements
3. catch exception
4. Statements
5. end

Statements between try and catch execute first. If no error appears in executing
statements between try and catch, MATLAB further executes the statements/code after
the end keyword. If an error occurs during the execution of statements between try and
catch, MATLAB executes statements between catch and end. Try-catch statement can be
explained with the help of the following example.

Example:

1. a = ones(4);
2. b = zeros(3);
3. try
4. c = [a;b];
5. catch ME
6. disp(ME)
7. end

Output:

MException with properties:

identifier: 'MATLAB:catenate:dimensionMismatch'
message: 'Dimensions of arrays being concatenated are not consistent.'
cause: {0×1 cell}
stack: [3×1 struct]
Correction: []
Following are the points while using a try/catch statement in MATLAB:

o The control of the program execution first enters the try block and executes each
statement.
o If any error occurs during the execution, then the control immediately passes to
the catch block, leaving any other statements of the try block unexecuted.
o If there is no error occurs inside try block, then the control doesn't enter the
catch block. The control then reaches to the statements after the end keyword of
try/ catch block.
o Whenever any error or exception occurs in the try block, the MATLAB constructs
an instance of the MException class and returns the object in the catch
statement.
o The MException class object can be accessed with the variable ME.
o The MException class object has five properties-identifier, message, stack,
cause, and Correction. These properties describe details about the occurred
exception.
o We can't use multiple catch block, only one catch block within a try block is
allowed.
o We can use nested try/catch blocks if required.

Example showing MException class object properties:

1. a = ones(4);
2. b = zeros(3);
3. try
4. c = [a;b];
5. catch ME
6. % strcmp string compare function, to check the same string in ME identifier
7. if (strcmp(ME.identifier,'MATLAB:catenate:dimensionMismatch'))
8. % if it is true then change the message property
9. msg = ['dimension mismatch occured: First argument has ',...
10. num2str(size(a,2)), ' columns, while second argument has ',...
11. num2str(size(b,2)),' columns.'];
12. causeException = MException('MATLAB:mycode:dimensions',msg)
13. ME = addCause(ME, causeException);
14. end
15.
16. end

Output:

causeException =
MException with properties:

identifier: 'MATLAB:mycode:dimensions'
message: 'dimension mismatch occured: First argument has 4 columns,
while second argument has 3 columns.'
cause: {}
stack: [0×1 struct]
Correction: []

Program Termination
Program termination control allows to exit from our program at some point before its
normal termination point.
MATLAB return
The command return simply return the control to the invoking function.

Example:

1. function animatebar (t0,tf,x0);


2. % animatebar animates a bar pendulum.
3. :
4. disp ('Do you want to see the phase portrait?')
5. ans = input ('Enter 1 if YES, 0 if NO');
6. if ans==0 % see text for description
7. return % if the input is 0
8. % exit function
9. else
10. plot (x,......) % show the phase plot
11. end

MATLAB end
The end keyword in MATLAB serves two main purposes:

1. It terminates a block of code.


2. It indicates the last array index.

MATLAB end syntax:


1. end

Example: Use end keyword to terminate the block of code:


1. a = ones(4)
2. for k = 1:length(a)
3. if a(k) == 1
4. a(k) = 0;
5. end
6. end
7. disp('......')
8. disp(a)
9. disp('...end')

Output:

a = 4×4
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
......
0 1 1 1
0 1 1 1
0 1 1 1
0 1 1 1
...end

Example: Use end keyword to indicate last array index:

1. a = randi(100,4,4)
2. b = a(end,2:end) % here first end argument indicates the last row,
3. %and the second indicates the columns number from 2 to the last
4. a = 4×4
5. 43 66 68 66
6. 92 4 76 18
7. 80 85 75 71
8. 96 94 40 4
9. b = 1×3
10. 94 40 4

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy