MATLAB:使用最小的矩阵更改-1的索引而不使用for循环

时间:2016-07-25 21:48:27

标签: arrays matlab matrix multidimensional-array

我用一个例子直接显示情况: 我有一个3x3x2

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

我想要做的是将-1值替换为相应的2D矩阵最小值。c(:,:,1)c(:,:,2)的最小值分别为2和{{1} }。 11的矩阵元素应替换为这些值。那么结果应该是:

-1

我现在所做的是:

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

我想在没有for循环的情况下替换最小值。有一个简单的方法吗?

1 个答案:

答案 0 :(得分:1)

这是一种方法:

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