Using a loop to clear multiple empty arrays at once
이전 댓글 표시
I've just begun using matlab for some data analyses, and have a program that dumps either 1 or 2 datasets into preallocated arrays depending on certain conditions. Currently, to get rid of empty datasets I use the following code:
if isempty(DSP01a)
clear DSP01a
end
if isempty(DSP02a)
clear DSP02a
end
This works fine for two datasets, but I've just begun working with a program that can generate up to 20 sets of data (e.g., DSP01a, DSP02a,....DSP20a), and repeating the above 20 times is ridiculously inefficient. So, is there any easy way to do this within a loop, replacing the '01', '02', '03'etc. on each loop?
Because of conventions in my workplace revamping the approach entirely isn't an option. Any help would be MUCH appreciated.
답변 (2개)
Sean de Wolski
2014년 4월 3일
편집: Sean de Wolski
2014년 4월 3일
0 개 추천
Star Strider
2014년 4월 3일
편집: Star Strider
2014년 4월 5일
See if this works:
DSP01 = rand(2);
DSP02 = [];
Datasets = 1:20;
for k1 = 1:length(Datasets)
DSName = sprintf('DSP%02da', k1);
e = eval(DSName);
if isempty(e)
clear e
sprintf('%s cleared\n', DSName)
end
end
It worked on the two matrices I created to test it with. Change it as needed.
EDIT — Forgot the ‘a’ after the number. Changed the sprintf statement to include it.
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!