How to delete a matrix using for loop and if condition?

4 visualizzazioni (ultimi 30 giorni)
Hello everyone,
I have two sets of matrices, Matrices A and Matrices B, so that there are
MA1, MA2, MA3 ..., MA100
and
MB7, MB13, MB18, .... there is no sequence.
I need to check if there is an MB matrix for every MA matrix, and if there is no MB for a certain MA then delete that MA matrix.
I tried to do the following process:
for i = 1:100
if exist(sprintf('MB%d',i),'var')
continue;
else
MLDeleteMatrix(sprintf('MA%d',i));
fprintf('MA%d has been deleted. \n', i);
end
end
I tried MLDeleteMatrix but it tells me:
Undefined function or variable
'MLDeleteMatrix'.
Can you please tell me how to do that?
  4 Commenti
Walter Roberson
Walter Roberson il 10 Gen 2020
MATLAB itself does not have a MLDeleteMatrix. However it does provide a function of that name of use with the interface between MATLAB and Excel. You cannot call the function inside MATLAB, only inside Excel or VBA.
You somehow encountered the wrong name to use to delete from inside MATLAB.
Stephen23
Stephen23 il 10 Gen 2020
"I have two sets of matrices, Matrices A and Matrices B, so that there are MA1, MA2, MA3 ..., MA100 and MB7, MB13, MB18, ...."
Putting numbers into variable names is a sign that you are doing something wrong.
Putting meta-data into variable names is a sign that you are doing something wrong.
Accessing variable names dynamically is one way that beginners force themselves into writing slow, complex, obfuscated, buggy code that is hard to debug. Read this to know why:
Exactly as the MATLAB documentation recommends, you should put your data into one array, then accessing it is trivial and efficient using indexing.

Accedi per commentare.

Risposte (1)

Cameron B
Cameron B il 10 Gen 2020
clear
clc
MA1 = ones(3);
MA2 = MA1*2;
MA3 = MA1*3;
MA4 = MA1*4;
MA5 = MA1*5;
MB2 = MA1*200;
MB4 = MA1*400;
for ii = 1:5
if exist(sprintf('MB%d',ii),'var')
continue;
else
clearvars(['MA',num2str(ii)])
fprintf('MA%d has been deleted \n',ii);
end
end
  1 Commento
Cameron B
Cameron B il 10 Gen 2020
I think you should consider another way to name your variables rather than MA1, MB1, etc. Dynamically naming variables is just asking for future headaches. Perhaps doing a 3D array with MA(:,:,1) = your previous MA1, MA(:,:,2) = your previous MA2, etc. Instead of not having MB(:,:,xx) data for one given value of xx, you could assign them as zeros. So in the case I showed above, you could rename MA(:,:,1), MA(:,:,3), and MA(:,:,5) to zeros instead of deleting them. This way, you’ll have an even number of MA and MB and won’t have to worry about finding and clearing the correct variables.

Accedi per commentare.

Categorie

Scopri di più su Data Import from MATLAB in Help Center e File Exchange

Prodotti


Release

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by