Aditya
Aditya

Reputation: 1268

Setting certain column value of each row in matlab

So I have a 150 X 4 matrix called Z.

I do some operation to this and what I have left is Z again.

[o p] = min(Z, [], 2);

Gives me the column number for each row.

I need to set that particular column for each row to 1 and rest to zero.

I thought of doing this but it didn't work out.

K = zeros(size(Z));
K(:, p) = 1;

Upvotes: 0

Views: 204

Answers (2)

Shai
Shai

Reputation: 114816

You can go through sparse:

K = full( sparse( 1:size(Z,1), p.', 1, size(Z,1), size(Z,2) ) );

Alternatively, you can use sub2ind:

K = zeros( size(Z) );
K( sub2ind( size(K), 1:size(K,1), p.' ) ) = 1;

If you are certain there is only one maximal element in each row you can

K = bsxfun( @eq, Z, o );

Upvotes: 2

Divakar
Divakar

Reputation: 221574

One approach -

K = zeros(size(Z))
K((p-1)*size(Z,1)+[1:size(Z,1)]')=1

Upvotes: 1

Related Questions