Removing zeros that may be in columns or rows, in efficient fast way
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Mohamed Abd El Raheem
el 10 de Dic. de 2021
Editada: Mohamed Abd El Raheem
el 11 de Dic. de 2021
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 comentarios
Respuesta aceptada
Voss
el 10 de Dic. de 2021
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
Más respuestas (1)
Image Analyst
el 10 de Dic. de 2021
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 comentarios
Image Analyst
el 11 de Dic. de 2021
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?
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!