Removing zeros that may be in columns or rows, in efficient fast way
조회 수: 4 (최근 30일)
이전 댓글 표시
Greetings:
I have some matrices in a big computaion task. Some of these matrices will have zero rows or zero columns as part of them. I can't decide in priori.
We want an efficient way to remove any whole zero row or whole zero column from any matrix that may appear during the computation.
The methods I found, to my knowledge, are all:
1- require a priori knowledge of : Are there whole zero rows or whole zero columns?
2- require knowledge of the required dimensions of the output matrix after zeros removal.
These two pieces of information are not available.
Example:
If computations yield X = [ 0 0 0 ; 1 1 1; 2 2 2 ] , make it X = [1 1 1; 2 2 2]
If they yield Y = [0 1 2; 0 1 2 ; 0 1 2] make it [1 2; 1 2 ; 1 2] and so on..
We don't know if the zeros appear on rows or columns. We don't know the number of zero rows or columns.
Any ideas?
댓글 수: 0
채택된 답변
Voss
2021년 12월 10일
X(:,~any(X,1)) = []; % remove columns which are all 0
X(~any(X,2),:) = []; % remove rows which are all 0
or an equivalent but maybe more clear way:
X(:,all(X == 0,1)) = []; % remove columns which are all 0
X(all(X == 0,2),:) = []; % remove rows which are all 0
추가 답변 (1개)
Image Analyst
2021년 12월 10일
Try this (untested)
X = [ 0 0 0 ; 1 1 1; 2 2 2 ]
rowsToRemove = all(X == 0, 2);
X(rowsToRemove, :) = [];
columnsToRemove = all(X == 0, 1);
X(:, columnsToRemove) = []
Y = [0 1 2; 0 1 2 ; 0 1 2]
rowsToRemove = all(Y == 0, 2);
Y(rowsToRemove, :) = [];
columnsToRemove = all(Y == 0, 1);
Y(:, columnsToRemove) = []
댓글 수: 3
Image Analyst
2021년 12월 11일
Yes, he posted his answer (essentially the same answer) just two minutes after mine. We were probably composing our answers at the same time. His second code sample is probably the more efficient one. Personally I think mine is less cryptic because I used well-named intermediate variables which will make it more maintainable should you pass the code on to others. Though he did use comments which will help make it less cryptic. Maybe you can at least "Vote" for mine.
I'm not sure what you're saying in your second paragraph. It takes however long as it takes, but it should be pretty fast, at least for matrices that are a few thousand rows or columns. How big are yours? Do they have millions of rows and columns?
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!