How to load variable listed in folder one at a time and run a script sequentially

1 view (last 30 days)
Dear all,
I have different .mat expressions (values) of the same variable VAR in a list of numerical arrays named differently stored in a folder: 'path to folder'\'array name'.VAR I want to import each VAR expression ('array name'.VAR) one at a time, run a script on the VAR value, name the output based on the 'array name' (such as 'array name'.OUTVAR), clear workspace except OUTVAR, then import the next VAR value on the list, run the same script, and iterate down the list. Please advise, I mention that 'array name' is not, say, 'file1', 'file2', but 'mark', 'john'
Many thanks,
Octavian

Accepted Answer

Walter Roberson
Walter Roberson on 8 Dec 2013
I suggest that instead of trying to create individual variables in the workspace for each array, that instead you use fields of a structure. For example,
ArrayName = 'mark';
results.(ArrayName) = ....
  1 Comment
Octavian
Octavian on 10 Dec 2013
Dear Walter,
Thank you, I used your suggestions and it works well for my case. Here is a code to import the same variable VAR from a list of .mat binary files originally generated by saving the variable values from the matlab workspace in a folder FOLDER. It searches for the variable by its name the list of .mat files in a FOLDER, in case this is a folder containing a mixt of .mat files, then it imports one VAR value from one file at a time (recursively), and runs a script on it, then imports the VAR value from the next in the trimmed list, runs the script again, etc:
% define directory or folder of matfiles
myFolder = 'path to folder/FOLDER';
if ~isdir(myFolder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s', myFolder);
uiwait(warndlg(errorMessage));
return;
end
% create first file name (fullFileName) cell array before import
filePattern = fullfile(myFolder, '*.mat');
matFiles = dir(filePattern);
for k = 1:length(matFiles)
baseFileName{k} = matFiles(k).name;
fullFileName{k} = fullfile(myFolder, baseFileName{k});
end
% create second file name (fullFileName) cell array/list containing only files that include var of interest
for k =1:length(fullFileName)
a{1,k} = {struct2cell(whos(matfile(fullFileName{k})))};
b(k) = strcmp(a{1,k}{1,1}{1,1},'VAR'); % b = index of file names including var of interest
end
fullFileName = fullFileName(b);
baseFileName = baseFileName(b)';
clear a b filePattern k matFiles myFolder
% recursively load file and process script
for i = 1: length(fullFileName)
load (fullFileName{i},'VAR');
... run script...
...clear all but fullFileName, and output OUTVAR...
Thank you,
Octavian

Sign in to comment.

More Answers (0)

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!