Mohammad
Mohammad

Reputation: 7418

How to replace a column of a specific value with zeros in Matlab?

I have a matrix like:

A=  
 1 2 7 4  
 3 2 8 5  
 2 2 9 6  

and wants to zero a column with only 2's and get something like:

A=  
 1 0 7 4  
 3 0 8 5  
 2 0 9 6  

Is there any clever way of doing this without two for loops?

Upvotes: 0

Views: 1711

Answers (1)

Shai
Shai

Reputation: 114786

You can use all to find a column of all 2's

all2 = all( A == 2, 1 ); % check along first dim
A(:,all2 ) = 0; % make column zero

If you want to set to zero all columns that are of the same number (not only 2) you can use to assist

allSame = all( bsxfun( @eq, A, A(1,:) ), 1 );
A( :, allSame ) = 0;

Upvotes: 4

Related Questions