查找每行矩阵的最小元素-MATLAB [英] Finding minimum elements of a matrix for each line - MATLAB

查看:474
本文介绍了查找每行矩阵的最小元素-MATLAB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是示例:

我有以下矩阵:

4 0 3
5 2 6
9 4 8

现在,我想找到两个最小值及其每行的索引.结果是:

Now, i want to find two minimum values, and their indexes for each row. So the result is:

row1: 0 , position (1,2) and 3, position (1,3)
row2...
row3....

好吧,我正在使用很多for循环,这非常复杂.那么使用MATLAB函数来实现我的目标的任何方法是吗?

Well i am using lots of for cycles, and it is pretty complex. So is the any way of using MATLAB function to achieve my goal?

我尝试过,但没有结果:

I have tried, but no result:

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

推荐答案

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

You can sort each row of your matrix in an ascending order, and then pick the first two indices for each row, like so:

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

现在val应该包含每行中前两个最小元素的值,而idx应该包含其列号.

Now val should contain the values of the first two smallest elements in each row, and idx should contain their column numbers.

如果要以格式化的方式在屏幕上打印所有内容(如您的问题所示),则可以使用功能强大的fprintf命令:

If you want to print everything on the screen in a formatted fashion (as shown in your question), you can use the all-mighty fprintf command:

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆