Maayan
Maayan

Reputation: 149

How can I skip the zeros in a matrix?

I have a matrix with columns filled with zeros and I want to copy the matrix into a new matrix but to skip the columns with the zeros.

Is there any command that can help me? I tried to do it with the sparse command but I didn't really understand what happens there. It skips the zeros but when you want to know how many columns you have in the new matrix it still shows the initial size.

Upvotes: 2

Views: 265

Answers (2)

Shai
Shai

Reputation: 114936

It's quite simple

>> noZeros = withZeros(:, any( withZeros, 1 ) )

The command any( withZeros, 1 ) returns a logical vector of length size(A,2) with true for each column in withZeros that has at least one non-zero entry.

Alternatively, you can drop the columns

>> withZeros(:, all( withZeros == 0, 1 ) ) = [];

Look at the documentation of any and all for more information.

Upvotes: 6

Yunus
Yunus

Reputation: 63

Let's say you have a random matrix with a size of 100x100

A = rand(100);

and let's assume the 15th column is zero

A(:,15) = 0;

Then you can delete this column with

A=A(:,any(A))

Upvotes: 6

Related Questions