Matlab:从某些矩阵中找到最小值并保存索引

时间:2014-04-21 01:53:59

标签: matlab matrix indexing min

假设我有矩阵:

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(以使计算更快)。有什么帮助如何编码吗?谢谢。

3 个答案:

答案 0 :(得分:3)

您可以像这样使用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 :(得分: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

答案 2 :(得分:1)

我认为这四行会做到这一点

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的解决方案几乎完全相同。我认为它不那么紧凑,但可读性稍差。