How can I compare the user input value in a given matrix.

6 views (last 30 days)
b=[ 10 32 54 76 -25
20 60 100 140 -51
45 135 -135 -45 59]
b1=input(' b1= ');
b2=input('b2= ');
b3=input('b3= ');
b4=input('b4= ');
if (b1==b(1)||b(6)||b(11))&&(b2==b(2)||b(7)||b(12))&&(b3==b(3)||b(8)||b(13))&&(b4==b(4)||b(9)||b(14))
disp('MATCH FOUND');
else
disp('MATCH NOT FOUND');
end
  1 Comment
jgg
jgg on 9 Jan 2016
I'm pretty sure your issue is that your or conditions are not written properly. Write them as full conditions.

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 9 Jan 2016
MATLAB does not have transitive "==" operators. (I don't know of any programming languages which do.) The section of code
(b1==b(1)||b(6)||b(11))
does not mean "(b1 is equal to b(1)), or (b1 is equal to b(6)), or (b1 is equal to b(11))". Each of the sections between the "||" is evaluated separately, so instead it means "(b1 is equal to b(1)), or (b(6) is true), or (b(11) is true)" and in MATLAB, a value is true if it is not 0. (Except that testing NaN in that syntax generates an error.)
If you want to test b1 against those three values, you need to write the "==" tests out,
b1 == b(1) || b1 == b(6) || b1 == b(11)
or you can use
ismember(b1, [b(1), b(6), b(11)])
or more compactly
ismember(b1, b([1 6 11]))
  2 Comments
Smita Banerjee
Smita Banerjee on 9 Jan 2016
Edited: Stephen23 on 9 Jan 2016
Thank you Sir, I have used
B=[b1 b2 b3 b4]
isequal (b(1,1:4),B)||isequal (b(2,1:4),B)||isequal (b(3,1:4),B)
Walter Roberson
Walter Roberson on 9 Jan 2016
Ummm, maybe. You did not really define what you wanted to test for, so I cannot tell whether that is correct or not. If that code is accurate it looks to me like it could be done as
B=[b1 b2 b3 b4];
ismember(B, b(:,1:4), 'rows')

Sign in to comment.

More Answers (0)

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!