【问题标题】:Matlab : find min value and save index from some matricesMatlab:从一些矩阵中找到最小值并保存索引
【发布时间】:2014-04-22 15:45:59
【问题描述】:

假设我有矩阵:

mat= [1 2 3;
      2 3 4;
      3 4 5;]

test = [2 3 4 5 6 7;
        3 4 5 6 7 8;
        7 8 9 4 5 6 ]

我想做的就是做这些操作:

mat1=[(1-2) (2-3) (3-4);
      (2-3) (3-4) (4-5);
      (3-7) (4-8) (5-9)] 

mat2=[(1-5) (2-6) (3-7);
      (2-6) (3-7) (4-8);
      (3-4) (4-5) (5-6)]

并保存mat1mat2 之间的最小值,然后保存值的索引。 我想要这样的答案:

ans = [-4 -4 -4;
       -4 -4 -4;
       -4 -4 -4]
index = [2 2 2;
         2 2 2;
         1 1 1]

我不需要保存mat1mat2,我只需要ansindex(以使计算更快)。有什么帮助如何编码吗?谢谢。

【问题讨论】:

  • 我知道矩阵 ans 来自哪里,但我很困惑你如何计算 index。第一步,您可以通过执行[mat mat] - test 计算mat1mat2,然后将结果分成两半。
  • index 保存最小值的来源路径,即给出最小值的矩阵,mat1还是mat2。

标签: matlab matrix indexing min


【解决方案1】:

您可以像这样使用bsxfun 来处理一般情况。

代码

%%// Slightly bigger example than the original one
mat= [
    1 2 3 6;
    2 3 4 2;
    3 4 5 3;]

test = [
    2 3 4 8 5 6 7 1;
    3 4 5 3 6 7 8 7;
    7 8 9 6 4 5 6 3]

[M,N] = size(mat);
[M1,N1] = size(test);

if N1~=2*N %%// Check if the sizes allow for the required op to be performed
    error('Operation could not be performed');
end

[min_vals,index] = min(bsxfun(@minus,mat,reshape(test,M,N,2)),[],3)

输出

min_vals =
    -4    -4    -4    -2
    -4    -4    -4    -5
    -4    -4    -4    -3

index =
     2     2     2     1
     2     2     2     2
     1     1     1     1

【讨论】:

  • +1 表示聪明和“密度”。但不确定这是否总能得到最清晰的答案(因为它很难阅读,这可能会导致问题发生 - 例如,如果其他人在 6 个月后查看您的代码)。
  • @Floris 我以后查找的工作流程将涉及分解为多个部分,它在大多数情况下都有效:) 顺便说一句!
【解决方案2】:
mat1 = mat-test(:,1:3)
mat2 = mat-test(:,4:end)
theMin = bsxfun(@min,mat1,mat2)

-4    -4    -4
-4    -4    -4
-4    -4    -4

建立索引

idx = mat2-mat1;
I2  = find(idx<=0);
I1  = find(idx>0);
idx(I2) = 2; 
idx(I1) = 1;

     2     2     2
     2     2     2
     1     1     1

【讨论】:

    【解决方案3】:

    我觉得这四行就可以了

    matDifs = bsxfun(@minus, mat, reshape(test, 3, 3, 2)); % construct the two difference matrices
    values = min(matDifs, [], 3); % minimum value along third dimension
    indices = ones(size(values)); % create matrix of indices: start out with ones
    indices(matDifs(:,:,2)<matDifs(:,:,1)) = 2; % set some indices to 2
    

    这与@Divakar 的解决方案几乎相同。我认为它不那么紧凑,但可读性稍强。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-16
      • 2011-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-30
      • 1970-01-01
      • 2013-09-13
      相关资源
      最近更新 更多