gpt4 book ai didi

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

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

例子如下:

我有以下矩阵:

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

最佳答案

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

[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)

关于matlab - 为每一行查找矩阵的最小元素 - MATLAB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14241978/

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