Question

I'm trying to increase the efficiency of my MATLAB code. What it does is, it replaces the nonzero elements of a matrix with the multiplication of the rest of the nonzero elements in the same row. For instance,

X = [2 3 6 0; 0 3 4 2]

transforms into

X = [18 12 6 0; 0 8 6 12]

It's an easy task to implement within a for loop. It checks every row, finds nonzero values and do its replacements. I want to get rid of the for loop though. Is there a way to implement this without a loop?

Was it helpful?

Solution

Code

X = [2 3 6 0; 0 3 4 2];

X1 = X;
X1(~X) = 1;

out = bsxfun(@rdivide,prod(X1,2),X1).*(X~=0)

Output

out =

    18    12     6     0
     0     8     6    12

OTHER TIPS

Probably getting the row product first once and then divide by the element you don't want is the simplest way:

X = [2 3 6 0; 0 3 4 2]
Y=X
%get the product of all elements in a row
Y(Y==0)=1
Y=prod(Y,2)
%repeat Y to match the size of X
Y=repmat(Y,1,size(X,2))
%For all but the zero elements, divide Y by X, which is the product of all other elements.
X(X~=0)=Y(X~=0)./X(X~=0)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top