为每一行查找矩阵中的最小元素 - MATLAB

3

以下是示例:

我有以下矩阵:


4 0 3
5 2 6
9 4 8

现在,我想找到每行的两个最小值及其索引。因此结果如下:
row1: 0 , position (1,2) and 3, position (1,3)
row2...
row3....

我正在使用很多for循环,这使得代码变得相当复杂。有没有使用MATLAB函数来实现我的目标的方法?

我已经尝试过了,但没有结果:

C=min(my_matrix,[],2)
[C(1),I] = MIN(my_matrix(1,:)) &find the position of the minimum value in row 1??

2
您可以使用 min 作为 [C,I] = min(...),其中 I 包含线性索引。请参阅 http://www.mathworks.com/help/matlab/ref/min.html - petrichor
我不理解那个结果。 - Oliver Charlesworth
我认为结果中的0后面缺少了 3,对吗? - petrichor
我想要每一行的“min”值以及它在矩阵中的位置作为结果。 - Marco
3个回答

4

您可以按升序对矩阵的每一行进行排序,然后选择每行的前两个索引,如下所示:

[A_sorted, I] = sort(A, 2);
val = A_sorted(:, 1:2)
idx = I(:, 1:2)

现在,val应该包含每行中前两个最小元素的值,idx应该包含它们的列号。
如果你想以格式化的方式将所有内容打印到屏幕上(如你的问题所示),你可以使用万能的fprintf命令:
rows = (1:size(A, 1))';
fprintf('row %d: %d, position (%d, %d) and %d, position (%d, %d)\n', ...
    [rows - 1, val(:, 1), rows, idx(:, 1), val(:, 2), rows, idx(:, 2)]')

示例

A = [4, 0, 3; 5, 2, 6; 9, 4, 8];

%// Find two smallest values in each row and their positions
[A_sorted, I] = sort(A, 2);
val = A_sorted(:, 1:2)
idx = I(:, 1:2)

%// Print the result
rows = (1:size(A, 1))';
fprintf('row %d: %d, position (%d, %d) and %d, position (%d, %d)\n', ...
    [rows - 1, val(:, 1), rows, idx(:, 1), val(:, 2), rows, idx(:, 2)]')

结果如下:
val =
     0     3
     2     5
     4     8

idx =
     2     3
     2     1
     2     3

格式化的输出如下:

row 0: 0, position (1, 2) and 3, position (1, 3)
row 1: 2, position (2, 2) and 5, position (2, 1)
row 2: 4, position (3, 2) and 8, position (3, 3)

2

您可以使用 sort 轻松完成此操作。

[A_sorted, idx] = sort(A,2); % specify that you want to sort along rows instead of columns

idx列包含A每行的最小值,第二列包含第二小的值的索引。

最小值可以从A_sorted中获取。


我认为这样做不会奏效。原帖作者想要独立地对每一行进行排序,而这种方法是将所有行作为一个整体进行排序。 - Eitan T

1
您可以像下面这样做,其中A是您的矩阵。
[min1, sub1] = min(A, [], 2);  % Gets the min element of each row
rowVec = [1:size(A,1)]';       % A column vector of row numbers to match sub1
ind1 = sub2ind(size(A), rowVec, sub1)  % Gets indices of matrix A where mins are
A2 = A;                        % Copy of A
A2(ind1) = NaN;                % Removes min elements of A
[min2, sub2] = min(A2, [], 2); % Gets your second min element of each row

min1将是您的最小值向量,min2将是每行第二个最小值向量。它们在该行中的相应索引将在sub1sub2中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接