How can I delete specific columns from a matrix?

I have a 3xn matrix of data, and anywhere that data is repeated I've converted it to a column of zeros. Now, I want to clear the zero columns and leave only the relevant data. How can I do this? I've tried:
for i = length(matrix):1
if matrix(1,i) == 0
matrix(:,i) = [];
end
end
and it doesn't work. Please help. Here is the matrix I'm currently working with:
Columns 1 through 15
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Columns 16 through 30
0 0 0 0 0 0 0 9 0 0 0 10 0 11 11
0 0 0 0 0 0 0 2 0 0 0 6 0 1 6
0 0 0 0 0 0 0 3 0 0 0 8 0 7 9
Columns 31 through 36
0 0 12 12 0 0
0 0 1 2 0 0
0 0 4 8 0 0

 채택된 답변

Guillaume
Guillaume 2017년 7월 3일
편집: Guillaume 2017년 7월 3일

0 개 추천

Of course, it does not work:
for i = length(matrix):1
I assume you're trying to run the loop in reverse so that you don't shift rows yet to process as you delete rows. That's not how you tell matlab to run a loop in reverse. You have to specify the increment/decrement. Also, never use length on a matrix. If your n is less than 3, it'll return the number of columns instead and leads to interesting bugs. Always use size with an explicit dimension. So:
for i = size(matrix, 2):-1:1
would work. However, a loop is just a waste of time when it can all be accomplished in just one line with:
matrix(:, matrix(1, :) == 0) = [];

댓글 수: 3

I tried that line and am getting an error message on the second colon. It says it's an "unexpected matlab operator." Any advice?
Sorry, an extra closing bracket got in there by mistake. Fixed now (and also edited to delete columns instead of rows as I misread your post.
Thanks so much! It works perfectly!

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Andrei Bobrov
Andrei Bobrov 2017년 7월 3일

0 개 추천

your_mtx = [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 9 0 0 0 10 0 11 11 0 0 12 12 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 6 0 1 6 0 0 1 2 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 0 0 0 8 0 7 9 0 0 4 8 0 0];
out = your_mtx(:,any(your_mtx));
Arezoo Samiei
Arezoo Samiei 2019년 4월 2일

0 개 추천

Use the following command is the other way
C = setdiff(A,B)

카테고리

도움말 센터File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

질문:

2017년 7월 3일

답변:

2019년 4월 2일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by