Toygan
Toygan

Reputation: 422

MATLAB: Changing indexes of -1 with minimum of matrix without for loop

I'm directly showing the situation with an example: I have a matrix which is 3x3x2

c(:,:,1) = [-1 2 3;
            -1 5 6;
             7 8 9];
c(:,:,2) = [ 11 12 -1;
             13 14 15;
             16 17 18];

What I want to do is replacing -1 values with corresponding minimum value of 2D matrix.The minimum of c(:,:,1) and c(:,:,2) are respectively 2 and 11. The matrix elements of -1 should be replaced these values. Then the result should be:

result(:,:,1) = [2 2 3;
                 2 5 6;
                 7 8 9];
result(:,:,2) = [ 11 12 11;
                  13 14 15;
                  16 17 18];

What I did up to now is:

d = max(c(:))+1;
c(c==-1) = d; 
e = reshape(c,9,2);
f = min(d);

I want to replace the minimum values without for loop. Is there a simple way for this?

Upvotes: 2

Views: 47

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112699

Here's a way to do it:

d = reshape(c,[],size(c,3)); % collapse first two dimensions into one
d(d==-1) = NaN; % replace -1 entries by NaN, so min won't use them
m = min(d,[],1); % minimum along the collapsed dimension
[ii, jj] = find(isnan(d)); % row and column indices of values to be replaced
d(ii+(jj-1)*size(d,1)) = m(jj); % replace with corresponding minima using linear indexing
result = reshape(d, size(c)); % reshape to obtain result

Upvotes: 1

Related Questions