【问题标题】:MATLAB: Changing indexes of -1 with minimum of matrix without for loopMATLAB:在没有for循环的情况下用最少的矩阵更改-1的索引
【发布时间】:2016-07-25 21:48:26
【问题描述】:

我直接用一个例子来说明情况: 我有一个矩阵是3x3x2

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

我想要做的是将-1值替换为二维矩阵的相应最小值。c(:,:,1)c(:,:,2)的最小值分别是211-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 循环的情况下替换最小值。有什么简单的方法吗?

【问题讨论】:

    标签: arrays matlab matrix multidimensional-array


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2013-02-16
      • 1970-01-01
      • 2019-12-06
      • 1970-01-01
      • 2016-10-31
      • 1970-01-01
      • 2013-02-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多