lecture 6 flow control
play

Lecture 6: Flow Control Lecture 6: Flow Control 1 / 28 Relational - PowerPoint PPT Presentation

Lecture 6: Flow Control Lecture 6: Flow Control 1 / 28 Relational Expressions Conditions in if statements use expressions that are conceptually either true or false . These expressions are called relational expressions or Boolean expressions


  1. Lecture 6: Flow Control Lecture 6: Flow Control 1 / 28

  2. Relational Expressions Conditions in if statements use expressions that are conceptually either true or false . These expressions are called relational expressions or Boolean expressions Operator Meaning > greater than less than < greater than or equals >= less than or equals <= equality == inequality ∼ = Lecture 6: Flow Control 2 / 28

  3. Logical Operators The result of a logical operation is 1 if it is true and 0 if it is false . Logical operators can be used to create compound statements that evaluate to true or false & logical AND | logical OR complements elements of A ∼ xor exclusive OR TRUE if all elements of an array are TRUE all TRUE if any elements of an array are TRUE any The following short circuit operators only work with scalars && : (exprA && exprB) - exprB is only evaluated if exprA is true . || : (exprA || exprB) - exprB is not evaluated if exprA is true Lecture 6: Flow Control 3 / 28

  4. Truth tables A B A & B A | B ∼ A xor(A,B) 0 0 0 0 1 0 0 1 0 1 1 1 1 0 0 1 0 1 1 1 1 1 0 0 Lecture 6: Flow Control 4 / 28

  5. Precidence rules Operator Operation Priority Highest NOT ∼ & AND | OR && short circuit AND || short circuit OR Lowest It is a good idea to use paranthesis on long expressions a|b&c is evaluated as a|(b&c) Lecture 6: Flow Control 5 / 28

  6. Precidence rules (always use parenthesis) > b=10; 1 > > 1 | b > 0 &0 2 > ans = 3 logical 4 1 5 > (1 | b > 0) &0 1 > ans = 2 logical 3 0 4 > 1 | (b > 0 &0) 1 > ans = 2 logical 3 1 4 Lecture 6: Flow Control 6 / 28

  7. Logical data types logical data types can be used to as indices for to extract specific elements of vectors > x= randi([-10,10],1,10) 1 > x = 2 9 -7 -5 -7 -8 8 2 1 -7 7 3 > x < 4 4 > ans = 5 1 1 0 logical array 6 0 1 1 1 1 0 1 1 1 0 7 > x(x < 4) 8 > ans = 9 -7 -5 -7 -8 2 1 -7 10 Lecture 6: Flow Control 7 / 28

  8. Logical data types However, not 0-1 vectors are logical data types > y=[3 5 6 1 8 2 9 4 0 7] 1 > y = 2 3 5 6 1 8 2 9 4 0 7 3 > rem(y,2) 4 > ans = 5 1 1 0 1 0 0 1 0 0 1 6 If we try to extract the odd entries as: > y(rem(y,2)) 1 > Array indices must be positive integers or logical ... 2 values. This is due to the fact that rem does not return a logical data type Lecture 6: Flow Control 8 / 28

  9. Logical data types We can use the logical function to fix this problem > y=[3 5 6 1 8 2 9 4 0 7] 1 > y = 2 3 5 6 1 8 2 9 4 0 7 3 > y(logical(rem(y,2))) 4 > ans = 5 3 5 1 9 7 6 Lecture 6: Flow Control 9 / 28

  10. find command We can extract elements from a vector satisfying a certain condition. > x=[1 1 1 4 5 2 1] 1 > x = 2 1 1 1 4 5 2 1 3 > find(x==1) 4 > ans = 5 1 2 3 7 6 > x(find(x==1)) 7 > ans = 8 1 1 1 1 9 find also works for matrices, check the documentation for usage Other useful commands: any and all Lecture 6: Flow Control 10 / 28

  11. Excercise 1 Write a function sum_primes that takes as input a vector or matrix and returns the sum of all prime numbers. 2 Write a function clean_data that takes as input a vector and replaces all elements greater than 10 or less than zero with NaN Lecture 6: Flow Control 11 / 28

  12. Selection control – if statements if-blocks are used to decide which instruction to execute next depending on wheather an expression is true or not. if ...end if logical_expression statement1 statement2 end if ...else ...end if logical_expression statements evaluated if TRUE else statements evaluated if FALSE end Lecture 6: Flow Control 12 / 28

  13. Selection control – if statements if-blocks are used to decide which instruction to execute next depending on wheather an expression is true or not. if ...elseif ...else ...end if logical_expression1 block of statements evaluated if logical_expression1 is TRUE elseif logical_expression2 block of statements evaluated if logical_expression2 is TRUE else block of statements evaluated if no other expression is TRUE end Lecture 6: Flow Control 13 / 28

  14. Selection control – if statements - Examples %selection statements 1 %if ...end 2 a=input('Enter an integer:'); 3 if(mod(a,2)==0) 4 fprintf('Your integer %d is even \ n',a); 5 end 6 7 %if...else...end 8 %we can add more feedback 9 if(mod(a,2)==0) 10 fprintf('Your integer %d is even \ n',a); 11 else 12 fprintf('Your integer %d is odd \ n',a); 13 end 14 Lecture 6: Flow Control 14 / 28

  15. Selection control – if statements - Examples %a code segment that categories height 1 height = input('Enter your feet:'); 2 if (height > 7) 3 disp ('very tall'); 4 elseif (height > 6) 5 disp ('tall'); 6 elseif ((height < 5) && (height > 0)) 7 disp ('short'); 8 else 9 fprintf('height value %f is not a positive ... 10 real \ n',height); end 11 Lecture 6: Flow Control 15 / 28

  16. Selection control – Switch/Case statements Switches between several cases depending on an expression, which is either a scalar or a string. a=input('Enter an integer:'); 1 switch(mod(a,2)) 2 case 0 3 fprintf('Your integer %d is even \ n',a); 4 case 1 5 fprintf('Your integer %d is odd \ n',a); 6 otherwise 7 fprintf('The number %f is not an integer \ n',a); 8 end 9 Handy for avoiding tedious if..elseif.. statements Lecture 6: Flow Control 16 / 28

  17. Iteration control – for Loop the for loop repeats a block of statements a fixed number of times. Usage: for index = first:step:last block of statements end Lecture 6: Flow Control 17 / 28

  18. Iteration control – for Loop Example Computing the sum of a geometric series with N terms, first term a and common ration r . S N = a + ar + ar 2 + ar 3 + . . . + ar N − 1 Exercise Write a for loop to compute the sum 1 + x + x 2 2! + x 3 3! + x 4 4! + . . . + x N N ! for any integer N Lecture 6: Flow Control 18 / 28

  19. Iteration control – for Loop (Example) Use a for loop to plot cos ( nx ) using subplots for n = 1 − 9 on [0 , 2 π ] Lecture 6: Flow Control 19 / 28

  20. Iteration control – for Loops (Example) Use a for loop to plot cos ( nx ) using subplots for n = 1 − 9 on [0 , 2 π ] %using for loops with subplot 1 clc 2 clf 3 x = linspace(0,2*pi); %default 100 pts 4 for n=1:9 5 subplot(3,3,n); 6 y = cos(n*x); 7 plot(x,y,'LineWidth',2); 8 xlabel('x'); 9 ylabel('y'); 10 str =['subplot ',num2str(n)]; 11 title(str); 12 axis tight 13 end 14 Lecture 6: Flow Control 20 / 28

  21. Iteration control – while Loop while loop evaluates a block of statements as long as the logical_expression is TRUE Usage while logical_expression block of statements ... end Convert the geom_series.m code to work with a while loop Lecture 6: Flow Control 21 / 28

  22. double for loop %double for loop 1 %PC MA302 2 clc 3 clear 4 x=[1 2 -1 5 7 2 4]; 5 y=[ 3 1 5 7]; 6 7 m = length(x); 8 n = length(y); 9 A=zeros(m,n); %preallocate memory 10 for i index =1:m 11 for j index =1:n 12 A(i index,j index) = x(i index)*y(j index); 13 end 14 end 15 disp(A); 16 Lecture 6: Flow Control 22 / 28

  23. double while loop %while loop 1 clc 2 clear 3 x=[1 2 -1 5 7 2 4]; 4 y=[ 3 1 5 7]; 5 m = length(x); 6 n = length(y); 7 A=zeros(m,n); %preallocate memory 8 i index=1; 9 10 while(i index ≤ m) 11 j index=1; 12 while(j index ≤ n) 13 A(i index,j index) = x(i index)*y(j index); 14 j index = j index+1; %increment j index 15 end %i index 16 i index = i index +1; %increament i index 17 end %i index 18 disp(A); 19 Lecture 6: Flow Control 23 / 28

  24. while – prompting user for better input %prompting user for better input 1 a = input('Enter a non-zero integer:'); 2 while((a==0) | | ( round(a) � = a)) 3 fprintf('Your input is not a nonzero integer \ n'); 4 a=input('Enter a non-zero integer:'); 5 end 6 7 %% 8 %stop if input format is incorrect 9 %% 10 a = input('Enter a non-zero integer:'); 11 while((a==0) | | ( round(a) � = a)) 12 error('Your input is not a nonzero integer, Try again'); 13 end 14 Lecture 6: Flow Control 24 / 28

  25. Other useful commands break - terminates the execution of a for or while loop. continue - passes control to the next iteration of a for or while loop return - stops execution of the function or script before the end error - throws an error exception and displays a message Lecture 6: Flow Control 25 / 28

  26. nargin, nargout, varargin, varargout nargin - returns the number of function input arguments given in the call to the current function. nargout - returns the number of function output arguments given in the call to the current function. varargin - an input variable that enables a function to accept any number of variables. varargout - output variable that allows a function to return any number of variables. The MATLAB function size is a good example to illustrate multiple output options Lecture 6: Flow Control 26 / 28

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend