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 个)

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 的更多信息

标签

提问:

Jim
2014-4-3

Community Treasure Hunt

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

Start Hunting!

Translated by