Yang
Yang

Reputation: 6892

Set the largest element in each row to be one and others zero

I have a matrix in MATLAB like

t2 =

    0.4366    0.4298    0.5907
    0.9401    0.5358    0.6136
    0.2305    0.5212    0.9759
    0.9545    0.5572    0.9042

I want to get the largest element on each row and set them to be one, the rest to be zero. So

t2 = 

      0    0    1
      1    0    0
      0    0    1
      1    0    0

How can I do that with the fewest commands?

Upvotes: 2

Views: 1705

Answers (4)

chappjc
chappjc

Reputation: 30579

Straightforward with sparse and the second output argument to max:

[~,icol] = max(M,[],2);
B = full(sparse(1:size(M,1),icol,1,size(M,1),size(M,2)))

Or with spconvert instead of sparse:

B = full(spconvert([(1:size(M,1))',icol,ones(size(M,1),1);[size(M) 0]]))

Test data:

M = [0.4366,0.4298,0.5907;...
     0.9401,0.5358,0.6136;...
     0.2305,0.5212,0.9759;...
     0.9545,0.5572,0.9042]; % OP's t2

Upvotes: 1

voxeloctree
voxeloctree

Reputation: 849

Here is an alternate example, not as elegant... but still nice and understandable. And gets the job done.

for i = 1:length(t2(:,1))
    t2(i,:)=t2(i,:)==max(t2(i,:));
end

Upvotes: 2

horchler
horchler

Reputation: 18484

A one-liner in Matlab:

t2 = [0.4366 0.4298 0.5907;
      0.9401 0.5358 0.6136;
      0.2305 0.5212 0.9759;
      0.9545 0.5572 0.9042];
t2 = double(bsxfun(@eq, t2, max(t2, [], 2)))

Upvotes: 3

ely
ely

Reputation: 77424

I'm not remembering the exact syntax for saying this in MATLAB right off hand, but here is how you can do it in Python with NumPy arrays, and the syntax will more or less be exactly the same in MATLAB. You won't use the None trick I've used to expand the array dimensions, though.

(Note: I used my own random set of data, not yours)

In [311]: t2/t2.max(axis=1)[:,None]
Out[311]:
array([[ 0.96452099,  0.19900529,  1.        ],
       [ 1.        ,  0.36581245,  0.91631999],
       [ 0.62747397,  0.96969966,  1.        ],
       [ 0.07238682,  0.59855665,  1.        ]])

In [312]: np.floor(t2/t2.max(axis=1)[:,None])
Out[312]:
array([[ 0.,  0.,  1.],
       [ 1.,  0.,  0.],
       [ 0.,  0.,  1.],
       [ 0.,  0.,  1.]])

Upvotes: 0

Related Questions