Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

matrix

matlab

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

like image 470
Tomas Aschan Avatar asked Mar 07 '11 23:03

Tomas Aschan


2 Answers

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.

like image 77
abcd Avatar answered Nov 16 '22 00:11

abcd


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.

like image 30
gnovice Avatar answered Nov 16 '22 00:11

gnovice