MATLAB: Reference .mat variable name after loading

dirfile referencefor loopload

I am trying to perform operations on a number of .mat files in a loop. The problem is that some of the loaded files do not come in with the variable name "maxtees". For example, some will be named "maxtees2000". Thus, I can not perform function that references "maxtees" (e.g., rows(maxtees)) when this isn't the appropriate variable name. Is there a way I can pull or reference these variables without having to re-save them all or set up different loops for different naming conventions? Thanks.
files = dir(['max*' '*.mat'])
maxT = [];
for i = 1:length(files)
load(files(i,1).name)
maxtees = maxtees(find(all(maxtees,2)),:);
maxtees = [gridNos maxtees(:,4) maxtees(:,5) maxtees(:,6) maxtees(:,9) maxtees(:,10)];
maxT = [maxT;maxtees];
end

Best Answer

Never load into the workspace directly, always load into a structure. Then your task is also much simpler, because it is easy to test for the existence of fields in that structure.
Here is a simple example, with variables named A and A100 in several mat files:
>> A = 0:3;
>> save('temp1.mat','A');
>> A = 4:6;
>> save('temp2.mat','A');
>> A100 = 7:9;
>> save('temp3.mat','A100');
Now clear the data and read those mat files back into MATLAB:
>> clear
>> D = dir('*.mat');
>> for k = 1:numel(D)
S = load(D(k).name);
F = fieldnames(S);
idx = strncmpi(F,'A',1); % you need to choose the best way to identify the variables.
vec = S.(F{idx}) % here is the data!
end
vec =
0 1 2 3
vec =
4 5 6
vec =
7 8 9
The best solution is to use exactly the same name in all of the mat files, because different variable names implies that you are storing meta-data in the variable name, which is not a good practice. Meta-data should be stored just like any other data, and not put into variable names. Read this for a more detailed explanation:
Also avoid "solutions" that use eval: using eval is a bad practice that removes all code helper tools and the JIT engine speed improvements (i.e. is not how you should be practicing writing code):
Related Question