Download presentation
Presentation is loading. Please wait.
Published byMorris Stanley Modified over 9 years ago
1
Conditional Logic in MATLAB By Bruce Raine
2
How to do a basic IF – END structure in MATLAB if MATLAB Commands end i.e. do the MATLAB commands if the conditional statement is true EX: >> if (a == b), disp('They equal each other'); end e.g. A ==B Relational operators (or comparators) > ==, =, ~= and other combos Logical operators> NOT (~), AND (&), logical OR (|), exclusive OR (xor)
3
Try these IF statements out (using ==, >) % set up conditional variables a = 5; b = a; % single-conditionals with many relationals/comparators disp('===================================') % uses == for equality if (a == b), disp('They equal each other'); end % uses == for equality if (a == 5), disp('a equals 5'); end %uses > if (a > 4), disp('a is greater than 4'); end
4
More IF statements using <= and LOGICAL AND (&) and LOGICAL NOT (TILDE,~) % uses <= if (b <= 7), disp('b is less than or equal to 7'); end b = 6; % uses TILDE for negation i.e. NOT EQUAL if (b ~= a), disp('b does not equal a'); end % a double condition using AND if a == 5 && b == 6, disp('they equal 5 and 6 respectively'); end
5
Even more IF statements (|, INCLUSIVE LOGICAL OR) % a double condition using INCLUSIVE OR b=7; if (a == 6 || b == 7), disp('one or other equals 6 or 7 respectively'); end % a double condition using numerical negation if -(a) == -5, disp('Negated a equals -5'); end
6
LOGICAL OR statements (using | and XOR) % a logical OR (either or both may be true) a=[1,0,0,1]; b=[0,1,1,1]; if (a | b), disp('Only one pair need be true'); end % exclusive OR (only one may be true) a1=[1 0 pi 0]; b1 =[0 1 0 1]; if xor(a1,b1), disp('A match'); end
7
IF _ ELSE _ END structure if MATLAB Commands % do this if the conditional statement proves true else MATLAB Commands % do this if the conditional statement proves false end % place in a script file >> a= 3; b =5; if a <= b, v = 300; else v = 600; end
8
IF-ELSEIF-ELSE-END structure if MATLAB Commands % do this if the conditional statement proves true elseif MATLAB Commands % do this if the conditional statement proves false else MATLAB Commands % do this if the elseif proves false end
9
IF-ELSEIF-ELSE-END example % place in a script file >> a= 4; b =5; if a < b, v = 300 elseif a > b v = 600 else v = 500 end
10
SWITCH-CASE statement SWITCH switch-expression case value1 MATLAB commands case value2 MATLAB commands case value3 MATLAB commands … otherwise MATLAB commands end
11
SWITCH-CASE example units = input(‘Enter new units (a, b, c): ’,’s’); Error = 0 switch units case ‘a’ case ‘b’ case ‘c’ otherwise Error = 1; end
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.