Difference between revisions of "MATLAB:Relational Operators"

From PrattWiki
Jump to navigation Jump to search
m
 
Line 37: Line 37:
 
<references />
 
<references />
  
[[Category:EGR 53]]
+
[[Category:EGR 103]]

Latest revision as of 20:31, 8 June 2012

Relational operators in MATLAB are those that compare entries in two matrices and return true (1) or false (0) in a logical matrix depending upon the nature of the relationship.

Relational Operators

There are six relational operators in MATLAB:

Operator Meaning Sample Code Sample Code Result
< less than [3 1 4 1 5] < [2 3 4 5 6] [0 1 0 1 1]
<= less than or equal to [3 1 4 1 5] <= [2 3 4 5 6] [0 1 1 1 1]
== equal to [3 1 4 1 5] == [2 3 4 5 6] [0 0 1 0 0]
>= greater than or equal to [3 1 4 1 5] >= [2 3 4 5 6] [1 0 1 0 0]
> greater than [3 1 4 1 5] > [2 3 4 5 6] [1 0 0 0 0]
~= not equal to [3 1 4 1 5] ~= [2 3 4 5 6] [1 1 0 1 1]

Common Errors

The most common errors with relational operators involve using two or more relational operators without connecting them with a logical operator. For instance, to ask if a matrix is between 3 and 5, a temptation is to write:

x = input('What is x? ');
InRange = 3 <= x <= 5

However, this does not act the way it is intended because of the nature of relational operators. The order of operations, when all the operations are relational operators, is to go from left to right, so the first thing that will happen is the 3<=x relation is calculated. This can only result in either a (1) for true or a (0) for false. Next, that value is compared with 5. And since it must always be less than 5, the statement above will always be true, irrespective of the actual contents of x. Asking multiple relational questions requires connecting them with logical operators; the correct version of the above code would be:

x = input('What is x? ');
InRange = 3 <= x & x <= 5

Questions

Post your questions by editing the discussion page of this article. Edit the page, then scroll to the bottom and add a question by putting in the characters *{{Q}}, followed by your question and finally your signature (with four tildes, i.e. ~~~~). Using the {{Q}} will automatically put the page in the category of pages with questions - other editors hoping to help out can then go to that category page to see where the questions are. See the page for Template:Q for details and examples.

External Links

References