Relational and Logical Operators

(Chps. 6.1-6.2 Pgs. 248-252)

 

·       In more sophisticated programming, you will often need to compare the values of scalar variables or arrays.  You can then take different courses of action depending on the relationship between your variables.  For example, if x=0, you know that evaluating 1/x may cause problems (as the answer is infinity).  Thus, it would be nice to be able to test to see if a variable is in fact equal to zero, for example.

 

·       The operations described on this page are most useful when combined with the “if” command which we will introduce shortly.  That’s were you’ll see the real application…

 

Relational Operators

 

·       MATLAB’s relational operators are as follows:

 

<                 (less than)

<=              (less than or equal to)

>                 (greater than)

>=              (greater than or equal to)

==              (equal to)

~=               (no equal to)

 

·       Let’s see what these do…

 

% define some variables to work with

x=0;

y=4;

z=5;

a=[1,2,3,4];

 

% Try some relational operators

r=(y<5)               % is y less than 5?   r=0 for no, r=1 for yes

r=(z<5)                % is z less than 5?

r=(z<=5)             % is z less than or equal to 5?

r=(a(1)<a(2))     % is first element of a less than its second element?

 

r=(x>y)      % is x greater than y?

r=(x>=0)   % is x greater than or equal to 0?

 

r=(x==y)    % is x equal to y?

r=(x==0)   % is x equal to 0?

 

r=(x~=y)  % is x not equal to y (x different from y)?

r=(x~=0)  % is x not eqal to 0 (other than 0)?

 

         

·       Note that r=0 if the relationship you indicate is not met (false).  The variable r=1 if the condition is met (true).  Thus, the variable r in the statement r=(z<5) is the answer to the question is z<5? 

 

·       You can compare arrays this way also, but for the sake of time, we will not cover that here.

 

Logical Operators

 

·       MATLAB also has logical operators in case you need to test combinations of things.  The most commonly used are:

 

&                (and)

|                  (or)

 

·       Here are examples of their use

 

 

% define some variables to work with

x=0;

y=4;

z=5;

a=[1,2,3,4];

 

% is y less than 5 and also greater than 0?   r=0 for no, r=1 for yes

% yes because y is in the range 0<y<5

r=(y<5)&(y>0)

 

% is z less than 5 or greater than 10?

% no because z=5, it is neither less than 5 or greater than 10.

r=(z<5)|(z>10)

 

% is 1st element in a less than 2nd and 3rd less than 4th?

% yep!

r=(a(1)<a(2)&(a(3)<a(4))  

 

% is z less than 0, or x and y equal to 0 and 4, respectively?

% yes because the second condition is met.

          r=(z<0) | ((x==0)&(y==4))