MATLAB: Access variables in several .mat files

access datafor loopmat files

Hi,
I have 4 .mat files, each one with the same variables. I want to access some of those variables for each of the files.
The variables I want to access are called 'RW_01', 'RW_02',….., 'RW_20' in each of the files, with size 1×160000.
The result should be a 4(files)x 20(variables) cell. Each one containing the information for that specific file and variable i.e. 1×160000
Can I get some help? Thanks

Best Answer

Here is a simpler, faster method, without using slow and buggy eval:
files = {'file1.mat', 'file2.mat', 'file3.mat', 'file4.mat'};
S = load(files{1});
for m = 2:numel(files)
S(m,1) = load(files{m});
end
C = struct2cell(S)';
and it gives exactly the cell array requested in the original question:
>> size(C)
ans =
4 20
>> size(C{1,1})
ans =
1 160000
This code assumes that the only fields in the mat files are those that are required. If there are other fields in the mat files, simply specify the required fields in the load call:
names = arrayfun(@(n)sprintf('RW_%02d',n),1:20,'Uni',false);
S = load(files{1},names{:});
etc.
Tip for beginners: rather than fighting MATLAB by using eval and other buggy, slow, and obfuscated commands, learn how to use MATLAB effectively by understanding matrices, arrays, and indexing:
A discussion of why eval is not the solution that beginners imagine it to be: