Tomas Aschan
Tomas Aschan

Reputation: 60564

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

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...)

Upvotes: 8

Views: 15057

Answers (3)

gnovice
gnovice

Reputation: 125854

First suggestion: don't use union as a variable name, since that will shadow the built-in function union. I'd suggest using the variable name inEitherOval instead since it's more descriptive...

Now, one option you have is to do something like what abcd suggests in which you add your matrices o1 and o2 and use the relational not equal to operator:

inEitherOval = (o1+o2) ~= 0;

A couple of other possibilities in the same vein use the logical not operator or the function logical:

inEitherOval = ~~(o1+o2);       % Double negation
inEitherOval = logical(o1+o2);  % Convert to logical type

However, the most succinct solution is to apply the logical or operator directly to o1 and o2:

inEitherOval = o1|o2;

Which will result in a value of 1 where either matrix is non-zero and zero otherwise.

Upvotes: 6

user3832800
user3832800

Reputation: 21

There is another simple solution, A=logical(A)

Upvotes: 2

abcd
abcd

Reputation: 42225

Simplest solution: A=A~=0;, where A is your matrix.

This just performs a logical operation that checks if each element is zero. So it returns 1 if the element is non-zero and 0 if it is zero.

Upvotes: 17

Related Questions