首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Matlab :从某些矩阵中求出最小值和保存索引

Matlab :从某些矩阵中求出最小值和保存索引
EN

Stack Overflow用户
提问于 2014-04-21 01:53:59
回答 3查看 382关注 0票数 1

假设我有矩阵:

代码语言:javascript
运行
复制
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 ]

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

代码语言:javascript
运行
复制
mat1=[(1-2) (2-3) (3-4);
      (2-3) (3-4) (4-5);
      (3-7) (4-8) (5-9)] 

代码语言:javascript
运行
复制
mat2=[(1-5) (2-6) (3-7);
      (2-6) (3-7) (4-8);
      (3-4) (4-5) (5-6)]

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

代码语言:javascript
运行
复制
ans = [-4 -4 -4;
       -4 -4 -4;
       -4 -4 -4]
index = [2 2 2;
         2 2 2;
         1 1 1]

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-04-21 04:57:31

您可以在广义情况下使用像这样的bsxfun

代码语言:javascript
运行
复制
%%// 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)

输出

代码语言:javascript
运行
复制
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
票数 3
EN

Stack Overflow用户

发布于 2014-04-21 02:14:10

代码语言:javascript
运行
复制
mat1 = mat-test(:,1:3)
mat2 = mat-test(:,4:end)
theMin = bsxfun(@min,mat1,mat2)

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

构建索引

代码语言:javascript
运行
复制
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
EN

Stack Overflow用户

发布于 2014-04-21 15:31:33

我想这四行行就行了

代码语言:javascript
运行
复制
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的解决方案几乎一样。它不那么紧凑,但我认为它的可读性更强。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23189695

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档