How to clear everything but a structure
6 views (last 30 days)
Show older comments
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
5 Comments
José-Luis
on 9 Sep 2017
"clear my workspace"
Does this mean that you are running a script instead of a function? You wouldn't have this problem if you used a function that returns only what you need. But that would just mask the problem anyway.
That being said you should follow Stephen's advice if you want to cut the problem from the source.
Accepted Answer
OCDER
on 9 Sep 2017
Edited: OCDER
on 9 Sep 2017
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)]).
2 Comments
Stephen23
on 10 Sep 2017
"Use clear or clearvars rarely because it's hard to track variables..."
They are also very slow.
More Answers (0)
See Also
Categories
Find more on Debugging and Analysis 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!