Weilliam
Weilliam

Reputation: 65

Assign zero to specific indices of a matrix in MATLAB

For example:

a = [1 2 3; 4 5 6; 7 8 9];   
b = [2 4]; %//Indices I got

How can I set to zero every element of a not indexed in b in order to obtain:

0 2 0  
4 0 0   
0 0 0

I tried for loop:

for i = 1:numel(a)  
    if i ~= b  
      a(i) = 0;
    end       
end

but the matrix I cope with is really large and it takes ridiculously long time to finish running.

Is there any smart way to do it? Thank you.

Upvotes: 2

Views: 77

Answers (2)

An alternative to Anton's direct solution is one based on copying:

a = [1 2 3; 4 5 6; 7 8 9];
b = [2 4]; 

atmp = a(b);
a = zeros(size(a));
a(b) = atmp;         %// copy needed elements

I guess efficiency of the two approaches boils down to allocation vs setdiff. Also, if your resulting matrix has many zeroes, you should perhaps consider using a sparse matrix.

Upvotes: 4

Anton
Anton

Reputation: 4684

Try this:

a = [1 2 3; 4 5 6; 7 8 9];
b = [2 4]; 

a(setdiff(1:length(a(:)),b)) = 0;

UPDATE

As proposed by @Daniel, for large matrices is better to use

a(setdiff(1:numel(a),b)) = 0;

Upvotes: 4

Related Questions