Reputation: 734
In MATLAB, I want to replace those entries in a matrix that their values equal to their row index with one, and the others with zero.
For example
A = [3 1 4
2 2 5
1 3 3];
and I want to have
B = [0 1 0
1 1 0
0 1 1];
Is there any way to do so efficiently?
Upvotes: 1
Views: 64
Reputation: 38032
Bit more generic:
MATLAB before R2016b:
B = bsxfun(@eq, A, (1:size(A,1)).');
MATLAB R2016b and later:
B = ( A == (1:size(A,1)).' );
Upvotes: 2
Reputation: 3364
k = size (A) ;
for i = 1 : k(1)
for j = 1 : k(2)
if (A(i,j) == i )
A(i,j) = 1;
else
A(i,j) = 0 ;
end
end
end
Alternative as per stewie suggestion:
bsxfun (@eq, A, [1,1,1;2,2,2;3,3,3])
Upvotes: 1