求每行矩阵的最小元素-MATLAB

求每行矩阵的最小元素-MATLAB,matlab,Matlab,以下是一个例子: 我有以下矩阵: 4 0 3 5 2 6 9 4 8 现在,我想找到两个最小值,以及每行的索引。因此,结果是: row1: 0 , position (1,2) and 3, position (1,3) row2... row3.... val = 0 3 2 5 4 8 idx = 2 3 2 1 2 3 嗯,我使用了大量的循环,这是相当复杂的。那么,使用MAT

以下是一个例子:

我有以下矩阵:

4 0 3
5 2 6
9 4 8
现在,我想找到两个最小值,以及每行的索引。因此,结果是:

row1: 0 , position (1,2) and 3, position (1,3)
row2...
row3....
val =
     0     3
     2     5
     4     8

idx =
     2     3
     2     1
     2     3
嗯,我使用了大量的循环,这是相当复杂的。那么,使用MATLAB函数实现我的目标有什么方法吗

我试过了,但没有结果:

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

您可以使用
排序
轻松完成此操作

[A_sorted, idx] = sort(A,2); % specify that you want to sort along rows instead of columns
idx
列包含
A
每行的最小值,第二列包含第二个最小值的索引


最小值可以从排序后的
A_

中检索。您可以执行如下操作,其中
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
您的每行第二小值向量。行的相应索引将在
sub1
sub2
中。您可以按升序对矩阵的每一行排序,然后为每一行选择前两个索引,如下所示:

[A_sorted, I] = sort(A, 2);
val = A_sorted(:, 1:2)
idx = I(:, 1:2)
现在,
val
应该包含每行中前两个最小元素的值,
idx
应该包含它们的列号

如果要以格式化方式打印屏幕上的所有内容(如问题中所示),可以使用all-Wighty
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)]')
例子 结果是:

row1: 0 , position (1,2) and 3, position (1,3)
row2...
row3....
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)

您可以使用
min
作为
[C,I]=min(…)
,其中
I
涉及线性指数。看,我不明白这个结果。我认为结果中0之后缺少
3
。?以及结果,我希望每行的“min”值,它在矩阵上的位置。我认为这不起作用。OP希望独立地对每一行进行排序,而这会将行作为一个组进行排序。