Using a loop to clear multiple empty arrays at once

1 view (last 30 days)
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.

Answers (2)

Sean de Wolski
Sean de Wolski on 3 Apr 2014
Edited: Sean de Wolski on 3 Apr 2014

Star Strider
Star Strider on 3 Apr 2014
Edited: Star Strider on 5 Apr 2014
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.

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!