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!