您可以按升序对矩阵的每一行进行排序,然后为每行选择前两个索引,如下所示:
[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)