I have two matrices, say X = [1 2; 3 4; 5 6] and Y = [0 1; -1 1; 1 1]. I want to perform element-wise division X./Y, but I need a way to ignore all the zeros in Y.
I tried using something like:
nonzeros = find(Y ~= 0); X(nonzeros) ./ Y(nonzeros);
but doing so caused the result to be a column vector, and I need the shape of the result matrix to be the same as X (or Y) and with zeros where Y was zero. So my desired result for this case is [0 2; -3 4; 5 6].
I also tried what was suggested here (Right Array Division : Ignoring division by zeroes), but doing this again forces the result to be a column vector.
Thanks
Use this -
out = X./Y %// Perform the elementwise division
out(Y==0)=0 %// Select the positions where Y is zero and
%// set those positions in the output to zero
Output -
X =
1 2
3 4
5 6
Y =
0 1
-1 1
1 1
out =
0 2
-3 4
5 6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With