Reputation: 45
I have two arrays in matlab (small part shown below):
A B
2 3
0,1 3,6
0,1 3,6
0,1 3,6
0,1 3,2
0 3,2
0 3,2
0 3,2
0 2,4
0 4,3
0,1 4,3
0,1 4,3
0,1 4,3
0,1 4,3
0,1 4,3
What I want to do: If value in column A is zero, value in column B should be changed to zero or NaN.
I would appreciate any help regarding this! I am new to matlab and I am not sure if a 'for - end' loop can/should be used?
Thanks! :)
Upvotes: 0
Views: 208
Reputation: 32930
You can use logical indexing:
B(A == 0) = 0;
The expression A == 0
returns a logical array (of booleans), containing "1"s at the positions that correspond to the zero elements in A
. Feeding this boolean array into B
, selects only the elements from B
at the locations of the "1"s. The zero assignment is self-explanatory.
However, when A
contains decimal values, Rody correctly pointed out that the comparison operation might be inaccurate and return false results. Therefore you should set a tolerance (e.g a multiple of eps
), like so:
tol = eps; %// Tolerance
B(abs(A) < tol) = 0;
If you don't care for floating point inaccuracy, and A
niether contains NaN
values nor complex numbers, you can use the following shortened syntax:
B(~A) = 0;
Upvotes: 4