MATLAB: How to clear everything but a structure

clear allefficiencyout of memory matlabstructures

Hello everyone,
In my code I have a huge for loop that runs several times for different text files that contain data. Each time the code runs I am able to extract a bunch of information and in the end I put the information that I want in a structure. The name of the structure is dependent of the ID of the text file.
So here is my problem, a bunch of variables in my work space are not needed after the structure is build. So how to I clear everything but the structures?
I can't use 'clearvars -except' because the name of the structure is dependent in the text file ID and there is no specific pattern to follow.
I am hoping clearing things from my work space would allow my code to run faster and solve the out of memory error I get in matlab.
Thank You,
M

Best Answer

Try wrapping your script for extracting Data from a File into a function called getFileData.
function Data = getFileData(File)
%Temporary variables can be created here.
Data = ......; %Do something to get Data from your File.
end %Temporary variables are cleared automatically!
Then in your script, fill up your structure S with data.
FileNames = {'file1.txt', 'file2.txt'};
S(1:length(FileNames)) = struct('Data', []); %Preallocate
for j = 1:length(FileNames)
S(j).Data = getFileData(FileNames{j});
end
The only variables in the workspace will be S and FileNames.
Use clear or clearvars rarely because it's hard to track variables you want to keep/remove when modifying codes, and you could accidentally delete variables.
If you want to access the jth data, use S(j).Data, which is MUCH BETTER than something like S.(['File' num2str(j)]).