Search code examples
matlabindices

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.


Solution

  • 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;