【问题标题】:Finding minimum elements of a matrix for each line - MATLAB为每行查找矩阵的最小元素 - MATLAB
【发布时间】:2013-01-10 04:19:13
【问题描述】:

示例如下:

我有以下矩阵:

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??

【问题讨论】:

  • 您可以将min 用作[C,I] = min(...),其中I 涉及线性索引。见mathworks.com/help/matlab/ref/min.html
  • 我不明白这个结果。
  • 我认为3 在结果中的 0 之后丢失了..?
  • 以及我想要每一行的“min”值的结果,它位于矩阵上

标签: matlab


【解决方案1】:

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

[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检索

    【讨论】:

    • 我认为这行不通。 OP 希望对每一行进行独立排序,而这会将行作为一个组进行排序。
    【解决方案3】:

    您可以执行以下操作,其中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

    【讨论】:

      猜你喜欢
      • 2023-04-09
      • 2016-02-17
      • 1970-01-01
      • 2021-01-13
      • 2011-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-18
      相关资源
      最近更新 更多