1

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?

0

2 Answers 2

2

Bit more generic:

MATLAB before R2016b:

B = bsxfun(@eq, A, (1:size(A,1)).'); 

MATLAB R2016b and later:

B = ( A == (1:size(A,1)).' ); 
Sign up to request clarification or add additional context in comments.

Comments

1
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]) 

1 Comment

@StewieGriffin: It was my mistake that I did not read his question properly. However, I added some code based on your suggestion in my answer. Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.