Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab element-wise division by zero

Tags:

matlab

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

like image 820
Danny Avatar asked Sep 16 '14 20:09

Danny


1 Answers

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
like image 145
Divakar Avatar answered Oct 04 '22 19:10

Divakar