Set all nonzero matrix elements to 1 (while keeping the others 0)

Posted by Tomas Lycken on Stack Overflow See other posts from Stack Overflow or by Tomas Lycken
Published on 2011-03-07T23:21:19Z Indexed on 2011/03/08 0:10 UTC
Read the original article Hit count: 132

Filed under:

I have a mesh grid defined as

[X, Y, Z] = meshgrid(-100:100, -100:100, 25); % z will have more values later

and two shapes (ovals, in this case):

x_offset_1 = 40;
x_offset_2 = -x_offset_1;
o1 = ((X-x_offset_1).^2./(2*Z).^2+Y.^2./Z.^2 <= 1);
o2 = ((X-x_offset_2).^2./(2*Z).^2+Y.^2./Z.^2 <= 1);

Now, I want to find all points that are nonzero in either oval. I tried

union = o1+o2;

but since I simply add them, the overlapping region will have a value of 2 instead of the desired 1.

How can I set all nonzero entries in the matrix to 1, regardless of their previous value?

(I tried normalized_union = union./union;, but then I end up with NaN in all 0 elements because I'm dividing by zero...)

Follow-up question:
I got a perfect answer to my original question, but now I have a follow-up question on the same problem. I'm going to define a filled disc, c = (X.^2+Y.^2<R^2) that will also overlap with the two ovals. How do I find all the points that are inside the circle, but not inside any of the ovals?

© Stack Overflow or respective owner

Related posts about matlab