user3070752
user3070752

Reputation: 734

Replace matrix entries in Matlab based on their value and their index

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

Answers (2)

Rody Oldenhuis
Rody Oldenhuis

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

User1551892
User1551892

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

Related Questions