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

3 views (last 30 days)
Mohamed Nedal on 10 Jan 2020
Commented: Stephen on 10 Jan 2020
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?
Stephen on 10 Jan 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.

Cameron B on 10 Jan 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
Cameron B on 10 Jan 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.

R2017b

### Community Treasure Hunt

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

Start Hunting!

Translated by