gpt4 book ai didi

matlab - 求矩阵元素匹配条件的索引 - Matlab

转载 作者:太空宇宙 更新时间:2023-11-03 19:51:24 25 4
gpt4 key购买 nike

给定一个矩阵 Z(i,j),它映射到两个数组 X(i) 和 Y(j)。我试图在一定范围内找到 Z 的元素(以及相应的 X 和 Y)。

我现在正在使用逻辑索引执行以下操作。给出这个例子

 X = 1:5;
Y = 1:5;
Z = [17 24 1 8 15
23 5 6 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9]
Z((X>1 & X<4),Y==3)

这工作正常,但现在我想从这个特定范围内找到返回值的最小值,

我用的是什么

min(Z((X>1 & X<4),Y==3))

但是现在我如何取回最小值对应的X和Y值呢?由于我的逻辑索引返回一个数组,所以到目前为止我尝试过的所有方法都返回答案数组中最小值的索引,而不是原始 Z 矩阵。

我不会用

[row col] = find(Z==min(Z((X>1 & X<4),Y==3)))

因为重复。我有哪些选择?

最佳答案

要检索原始索引,您必须在 xy 上保留两个条件的索引的内存(我将其放入数组 cXcY) 然后使用函数 ind2sub .

NB: your code is a little bit confusing since x stands for the lines and y for the columns, but I have kept the same convention in my answer.

在实践中,这给出了:

% --- Definition
X = 1:5;
Y = 1:5;
Z = [17 24 1 8 15
23 5 6 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9];

% --- Get the values of interest
cX = find(X>1 & X<4);
cY = find(Y==3);
v = Z(cX,cY);

% --- Get position of the minimum in the initial array
[~, I] = min(v(:));
[Ix, Iy] = ind2sub([numel(cX) numel(cY)], I);

i = cX(Ix); % i = 2
j = cY(Iy); % j = 3

最好的,

关于matlab - 求矩阵元素匹配条件的索引 - Matlab,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28996565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com