MATLAB Answers

0

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

Asked by Octavian on 8 Dec 2013
Latest activity Commented on by Octavian on 10 Dec 2013
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

  0 Comments

Sign in to comment.

1 Answer

Answer by Walter Roberson
on 8 Dec 2013
 Accepted Answer

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

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.