How to delete or exclude an entire matrix if it contains all zeros

I'm reading a large data set where sometimes there is a matrix of all zeros in all rows and columns. How do I either delete the entire matrix of zeros after it has been read, or exclude MATLAB from saving it in the first place?

 Risposta accettata

@Caitlin, you'll have to be more specific about how you are reading in the data in order to get a useful answer.
X=zeros(10,10);
whos % show variables in the workspace
Name Size Bytes Class Attributes X 10x10 800 double cmdout 1x33 66 char
You can delete variable X with
clear X
whos
Name Size Bytes Class Attributes cmdout 1x33 66 char
The output from whos shows that X is gone now.

4 Commenti

@Caitlin, if you're not sure if a matrix is all zeros, you can check quickly with
any(X,'all')
Example:
X=zeros(10,10);
Y=X; Y(4,6)=1e-6;
any(X,'all') % returns 0 iff all elements of X=0
ans = logical
0
any(Y,'all')
ans = logical
1
You asked "How do I either delete the entire matrix of zeros after it has been read, or exclude MATLAB from saving it in the first place?" If, by "saving", you mean "having the variable in the workspace", then you can't exclude that, if you don't know ahead of time, because you must read it in to find out whether it is all zeros. Then you can check it and clear it, if desired.
@William Rose Thank you so much! Very helpful.
If this Answer solves your original question, then could you please click the "Accept this answer" link to award the answerer with "reputation points" for their efforts in helping you? They'd appreciate it. Thanks in advance. 🙂 Note: you can only accept one answer (so pick the best one) but you can click the "Vote" icon for as many Answers as you want. Voting for an answer will also award reputation points.

Accedi per commentare.

Più risposte (0)

Categorie

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by