Arrays MATLAB:在不使用for循环的情况下,使用矩阵的最小值更改-1的索引
我用一个例子直接展示了这种情况: 我有一个矩阵是Arrays MATLAB:在不使用for循环的情况下,使用矩阵的最小值更改-1的索引,arrays,matlab,matrix,multidimensional-array,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]; 我想做的是用2D矩阵的相应最小值替换-1值。c(:,:,1)和c(:,:,2)的最小值分别是2和11。这些值应替换-1的矩阵元素。那么结果应该是: result(:,:,1)
3x3x2
c(:,:,1) = [-1 2 3;
-1 5 6;
7 8 9];
c(:,:,2) = [ 11 12 -1;
13 14 15;
16 17 18];
我想做的是用2D矩阵的相应最小值替换-1
值。c(:,:,1)
和c(:,:,2)
的最小值分别是2
和11
。这些值应替换-1
的矩阵元素。那么结果应该是:
result(:,:,1) = [2 2 3;
2 5 6;
7 8 9];
result(:,:,2) = [ 11 12 11;
13 14 15;
16 17 18];
到目前为止,我所做的是:
d = max(c(:))+1;
c(c==-1) = d;
e = reshape(c,9,2);
f = min(d);
我想替换没有for循环的最小值。有什么简单的方法吗?这里有一个方法:
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