How to check whether there is a particular element in a row vector?

3 views (last 30 days)
Consider the row vector CR2 (matrix attached). I want to check whether any of its element is equal to 0.2. In this case CR2 actually contains 0.2 (position 57), but if I type sum(CR2==0.2) I get zero. Could you help me in fixing this? Thank you!

Accepted Answer

Jan
Jan on 23 Mar 2014
Inspect the difference between the 57th element and 0.2:
disp(CR2(57) - 0.2)
What do you get?
  2 Comments
Image Analyst
Image Analyst on 23 Mar 2014
I'm sure he does, and so do I, as I started you out with my code. Not sure what you want to do after that so I leave it for you to finish.

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 23 Mar 2014
See the FAQ: http://matlab.wikia.com/wiki/FAQ#Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero.3F So you can't just test for equality and you need to check for some tolerance or find the min. Jan's suggestion of looking at the min difference is a good idea. Follow that up with a call to min and be sure to get the second return argument:
absDiff = abs(CR2 - 0.2)
[minDifference, indexAtMin] = min(absDiff);
if minDifference < 0.0001 % or whatever tolerance you want
% and so on......
(I assume you were honest when you did not tag it as homework. I hope this wasn't your homework I just did for you, or now you might need to find another way to do it. It can be done with a for loop and an if test.)

Categories

Find more on Programming 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!