如何在每一行中找到最大值并将其转换为特定值

时间:2014-04-13 14:20:36

标签: arrays matlab matrix indexing rows

我有一个像这样的矩阵:

0.1  0.2  0.5
0.3  0.7  0.4

我知道我可以使用max函数来查找每行的最大值。如何使用从max返回的索引来创建这样的新矩阵:

0  0  1
0  1  0

2 个答案:

答案 0 :(得分:4)

result = bsxfun(@eq, A, max(A,[],2));

答案 1 :(得分:3)

<强>代码

%%// Given matrix
A= [0.1  0.2  0.5;0.3  0.7  0.4]

%%// Get the column indices of max values across each row into y1
[~,y1] = max(A,[],2);

%%// Create a zero matix of size same as A and set the values corresponding
%%// to y1 along each row as 1 
A1 = zeros(size(A));
A1(sub2ind(size(A1),1:numel(y1),y1'))=1

<强>输出

A =

    0.1000    0.2000    0.5000
    0.3000    0.7000    0.4000


A1 =

     0     0     1
     0     1     0