MATLAB Answers

Anton Mulder

How to change an entire column.

Asked by Anton Mulder
on 29 Apr 2013


I have a matrix with a dimension of 10x640. The matrix is filled with ones and zeros. If there is a zero in one of columns, I want the entire column to be zeros. How can I do this?



Output should be:




No products are associated with this question.

2 Answers

Answer by Iman Ansari
on 29 Apr 2013
 Accepted answer

 A = randi(10,[10 640])-1;
 B = A;

  1 Comment

Jan Simon
on 29 Apr 2013

any(A, 2) is faster than sum(A==0)>0.

Answer by Image Analyst
on 29 Apr 2013

Try this:

% Make sample data.
A = ones(10, 640);
% Stick a zero in columns 3, and 5.
A(9, 3) = 0;
A(8, 5) = 0
% Now that we have some sample data, do what Anton wants.
% Find out which columns have zeros in them
columnsWithZeros = any(~A);  % Assumes A is only 0's and 1's.
A(:, columnsWithZeros) = 0; % Set whole column(s) to zero.

  1 Comment

If you want a terse "one-liner" you can do this:

A(:, any(~A)) = 0;

Join the 15-year community celebration.

Play games and win prizes!

Learn more
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!