Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
15 views

Matlab - Tutor5 - Logic2

Uploaded by

Gemini Goel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Matlab - Tutor5 - Logic2

Uploaded by

Gemini Goel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

MATLAB nested if-else

o If statements can be nested, but each if statement requires the end keyword.

Syntax:

1. if expression
2. Statements
3. if expression
4. Statements
5. else
6. Statements
7. end
8. elseif expression
9. Statements
10. if expression
11. Statements
12. end
13. else
14. Statements
15. end

Example1

1. % nested if-elseif-else program


2. num = randi(100,1);
3. a = input('enter a number greater than 1 and less than 10 : ')
4. disp(['the random number is : ', num2str(num)])
5. if a <= 1 || a >= 10
6. disp('please try again & enter the number in between 1 & 10')
7. elseif rem(num,a) == 0
8. if rem(num,2) == 0
9. if rem(a,2) == 0
10. disp('you entered an even number, and the random number is also even')
11. else
12. disp('random number is even and divisible by the entered number')
13. end
14. else
15. disp('random number is odd but divisible by the entered number')
16. end
17. elseif num < a
18. disp('random number is smaller than the entered number, please try again ')
19. else
20. disp('random number is not divisible by the entered number')
21. end

Output:

enter a number greater than 1 and less than 10: 9


a = 9
the random number is: 14
the random number is not divisible by the entered number

Example 2:

1. % create a random number, max. 100, and a scalar


2. a = randi(100,1)
3. % use quorem function(takes symbolic variables as arguments) to get quotient & remai
nder
4. [Q,R] = quorem(sym(a),sym(2))
5. if R == 0
6.
7. if rem(Q,2) == 0
8. disp('random number-even')
9. disp('result-even')
10.
11. else
12. disp('random number-even')
13. disp('result-odd')
14. end
15. else
16. if rem(Q,2) == 0
17. disp('random number-odd')
18. disp('result-even')
19.
20. else
21. disp('random number-odd')
22. disp('result-odd')
23. end
24. end

MATLAB switch
The switch is another type of conditional statement and executes one of the group of
several statements.

ADVERTISEMENT

o If we want to test the equality against a pre-defined set of rules, then the switch
statement can be an alternative of the if statement.

Syntax:

1. switch switch_expression
2. case case_expression1
3. Statements
4. case case_expression2
5. Statements
6. case case_expressionN
7. Statements
8. otherwise
9. Statements
10. End

Flowchart of Switch statement


Following are the points while using switch in MATLAB:
Similar to if block, the switch block tests each case until one of the case_expression is
true. It is evaluated as:

o case & switch must be equal for numbers as- case_expression == switch_expression.
o For character vectors, the result returned by the strcmp function must be equal to 1 as -
strcmp(case_expression, switch_expression) == 1.
o For object, case_expression == switch_expression.
o For a cell array, at least one of the elements of the cell array in case_expression must
match switch_expression.
o switch statement doesn't test for inequality, so a case_expression cannot include
relational operators such as < or > for comparison against the switch_expression.
Example1:

1. % program to check whether the entered number is a weekday or not


2. a = input('enter a number : ')
3. switch a
4. case 1
5. disp('Monday')
6. case 2
7. disp('Tuesday')
8. case 3
9. disp('Wednesday')
10. case 4
11. disp('Thursday')
12. case 5
13. disp('Friday')
14. case 6
15. disp('Saturday')
16. case 7
17. disp('Sunday')
18. otherwise
19. disp('not a weekday')
20. end

Output:

enter a number: 4
Thursday

Example2:

1. % Program to find the weekday of a given date


2. % take date input from keyboard in the specified format
3. d = input('enter a date in the format- dd-mmm-yyyy:',"s")
4. % weekday function takes input argument
5. % and returns the day number & day name of the particular date.
6. [dayNumber, dayName] = weekday(d,'long',"local");
7. % use switch and case to display the output as per the entered input
8. switch dayNumber
9. case 2
10. x = sprintf('Start of the week-%s-:%d',dayName,dayNumber);
11. disp(x)
12. case 3
13. x = sprintf('%s:%d',dayName,dayNumber);
14. disp(x)
15. case 4
16. x = sprintf('%s:%d',dayName,dayNumber);
17. disp(x)
18. case 5
19. x = sprintf('%s:%d',dayName,dayNumber);
20. disp(x)
21. case 6
22. x = sprintf('Last working day-%s-of the week:%d',dayName,dayNumber);
23. disp(x)
24. otherwise
25. disp('weekend')
26. end

MATLAB Loops
A loop statement allow us to execute a statement or group of statements multiple
times.

MATLAB provides different types of loops to handle looping requirements, including


while loops, for loops, and nested loops. If we are trying to declare or write our own
loops, we need to make sure that the loops are written as scripts and not directly in the
Command Window.

Two additional command, break and continue, can be used to create a third type of
loop, known as midpoint break loop. Midpoint break loop is useful for situations where
the commands in the loop must be executed at least once, but where the decision to
exit the loop is based on some criterion.

Types of Loops
There are two types of loop in MATLAB.

PauseNext
Mute

Current Time 0:01

Duration 18:10
Loaded: 2.94%
Â
Fullscreen
ADVERTISEMENT

1. for
2. while

for loop
A for loop is used to repeat a statement or a group of statements for a fixed number of
times.

Syntax

1. for index = values


2. <program statements>
3. ...
4. end

while loop
A while loop is used to execute a statement or a group of statements for an indefinite
number of times until the conditional specified by while is no longer satisfied.

Syntax

1. while <expression>
2. <statements>
3. end

MATLAB for loop


The for loop is used to loop the statements a specific number of times. And it also keeps
track of each iteration with an incrementing or decrementing index variable.

Syntax:

1. for index = values


2. <program statements>
3. ...
4. end

Example1:

1. % program to print multiples of first prime number between 1000 and 2000
2. % using for loop
3. pr = 0;
4. for k = 1000:2000
5. if isprime(k)
6. pr = k;
7. disp(['The first prime number is : ',num2str(pr)])
8. for m = pr:pr:pr*10
9. disp(m)
10. end
11.
12. break
13. end
14. end

Output:

The first prime number is: 1009


1009

2018

3027

4036

5045

6054

7063

8072

9081

10090

Example2:

1. for a = 10:20
2. fprintf('value of a: %d\n', a);
3. end

Output:

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 20
Example3:

1. for a = 1.0: -0.1: 0.0


2. disp(a)
3. end

Output:

PauseNext
Mute

Current Time 0:00

Duration 18:10
Loaded: 2.94%
Â
Fullscreen
1
9/10
4/5
7/10
3/5
1/2
2/5
3/10
1/5
1/10
0

MATLAB while loop


The while loop repeatedly executes statements while a specified statement is true.

Syntax:

1. while <expression>
2. <statements>
3. end

Example1:
1. % program to find the number ten from a series of random numbers
2. % using while loop
3. k = 1;
4. while k
5. if randi(50,1) == 10
6. disp(['The random number equivalent to 10 found at ',num2str(k),' step'])
7. break
8. end
9. k = k + 1;
10. end

Output:

The random number equivalent to 10 found at 36 step

Example2:

1. a = 10;
2. % while loop execution
3. while( a < 20 )
4. fprintf('value of a: %d\n', a);
5. a = a + 1;
6. end

Output:

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

MATLAB Nested Loop


MATLAB also allows using one loop inside another loops.

The syntax for the nested for loop statement in MATLAB is as follows:
1. for m = 1:j
2. for n = 1:k
3. <statements>;
4.
5. end
6. end

The syntax for the nested while loop statement in MATLAB is as follows:

1. while <expression1>
2. while <expression2>
3. <statements>
4. end
5. end

Example:
We can use the nested for loop to display all the prime numbers from 1 to 100.

PauseNext
Mute

Current Time 0:00

Duration 18:10
Loaded: 2.94%
Â
Fullscreen
ADVERTISEMENT

1. for i=2:100
2. for j=2:100
3. if(~mod(i, j))
4. break; % if factor found, not prime
5. end
6. end
7. if(j > (i/j))
8. fprintf('%d is prime\n', i);
9. end
10. end

Output:

2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime

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: 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
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:
PlayNext
Mute

Current Time 0:00

Duration 18:10
Loaded: 2.94%
Â
Fullscreen
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

MATLAB continue
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('....')

You might also like