How to find out if X is an element in an array, and then create another array based on that?

Hi everyone,
I am trying to do the following. I would like to determine if a specific value exists in an array. If it does, I would like to put a "1" in the same position in a second array (this array would be the same size as the first array). If it does not, I would like to put a "0" in the position in the second array. For example, if I am trying to find the number "2" in: A=[1 2 5; 3 2 9; 1 5 2] the second matrix would be: B=[0 1 0; 0 1 0; 0 0 1]
I know this most likely involves the use of the find command, I just can't get the details straight in my code (if it matters, my numbers will not be integers). I would appreciate any help.
Thanks,
Frank

Answers (1)

For integers
B = A == 2
for non-integers
B = abs(A-2) <= 10*eps

3 Comments

Thank you so much. This is great.
One question. Since the numbers are floats, so I need to worry about the "A == 2" portion of this command? Is there a way to set a tolerance?
It's also worth pointing out that the value of 'eps' is not a constant, and just indicates the distance from abs(x) to the next highest value. Typing 'eps' is just a short-hand version of 'eps(1)'. The distances between values is not constant when working with floating point precision numbers and increases as your numbers get larger.
If your values of A in the example above are very large then you should use a more appropriate value of eps, such as:
B = abs(A-2) <= eps(max(A))*10
However, doing this might give you false positives for smaller numbers.
@Frank, I don't understand what you are asking. The second part of the answer sets the tolerance.
@CJ, good points. I think in this case eps(2), and more generally eps(X), is probably better than eps(max(A(:))), but I don't know what would be best

Sign in to comment.

Categories

Find more on Linear Algebra in Help Center and File Exchange

Tags

Asked:

on 17 Jul 2012

Community Treasure Hunt

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

Start Hunting!