MATLAB: Loading Multiple .mat files, but not into structure

loadworkspace

Hello,
I have found many codes for loading multiple .mat files into the workspace, but it loads them into a structure. I would like the files loaded into the workspace as separate matrices and each named differently for each file (i.e. shape1, shape2 etc. I have 8000 files and would eventually like to take the average each grid cell between all the 8000 matrices (not sure how to do this within a structure though, so I prefer to load them all as separate matrices in the workspace).
Thank you

Best Answer

"not sure how to do this within a structure though"
So now is a good time to learn! Instead of learning the worst way of doing this task, why not take the opportunity of learning an efficient and robust way of doing this task ?
Creating lots of variables is possible, but it would be the slowest, buggiest, and very complicated solution. What do you imagine that you are going to do with 8000 variable in your workspace ? Loop over them and join them together ? Hint: this is possible, but very slow, buggy, and hard to debug. Read this to know why:
So load returns data in a structure, but it is easy to join them together. Here is an example, first we create some fake data:
>> A = 1:3;
>> save('file1.mat','A');
>> A = 4:6;
>> save('file2.mat','A');
>> A = 7:9;
>> save('file3.mat','A');
Now we get a list of those mat files, and read them in a loop:
>> S = dir('*.mat');
>> for k = 1:numel(S), tmp = load(S(k).name); S(k).A = tmp.A; end
Now all the data is in structure S, and it is easy to access:
>> vertcat(S.A)
ans =
1 2 3
4 5 6
7 8 9
>> S(3).A
ans =
7 8 9
Of course you don't have to store the data in a structure, it is also trivial to store them in an array:
>> S = dir('*.mat');
>> M = NaN(numel(S),3);
>> for k = 1:numel(S), tmp = load(S(k).name); M(k,:) = tmp.A; end
>> M
M =
1 2 3
4 5 6
7 8 9