How to delete a matrix using for loop and if condition?
1 回表示 (過去 30 日間)
古いコメントを表示
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 件のコメント
Walter Roberson
2020 年 1 月 10 日
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
2020 年 1 月 10 日
"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.
回答 (1 件)
Cameron B
2020 年 1 月 10 日
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 件のコメント
Cameron B
2020 年 1 月 10 日
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.
参考
カテゴリ
Help Center および File Exchange で Data Import from MATLAB についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!