Automate the opening of .mat files and the aggregation of opened matricies

1 view (last 30 days)
I wasn't sure how to title this question. It's pretty easy to describe what I'm trying to do, though:
I have 100 .mat files, with names output1.mat through output100.mat. Each of these contains a matrix, with the name of the matrix being matrix1 though matrix100 (output1.mat contains matrix1, output2 contains matrix2, etc.)
I would like to create one matrix "Result" which contains the first column of each of the above matricies. So, column1 would be the first column of matrix1, column2 would be the first column of matrix2, etc.

Accepted Answer

Stephen23
Stephen23 on 17 Jun 2016
Edited: Stephen23 on 17 Jun 2016
My code correctly preallocates the output matrix, and does not assume that the matrix is the only variable in the mat file:
%Some fake data:
matrix1 = randi(9,5)
matrix2 = randi(9,5)
matrix3 = randi(9,5)
matrix4 = randi(9,5)
save('output1.mat','matrix1') % better would be to use
save('output2.mat','matrix2') % the same variable name.
save('output3.mat','matrix3')
save('output4.mat','matrix4')
%
% import those |.mat| files:
out = NaN(5,4); % preallocate the output
for k = 1:4
S = load(sprintf('output%d.mat',k));
tmp = S.(sprintf('matrix%d',k));
out(:,k) = tmp(:,1);
end
and tested:
matrix1 =
3 2 5 6 5
3 9 2 7 9
1 2 5 3 3
6 6 3 5 3
8 8 8 4 4
matrix2 =
7 8 2 2 6
6 2 7 6 1
9 6 3 4 7
1 5 2 5 7
5 3 2 8 9
matrix3 =
5 4 1 4 5
6 5 6 3 4
2 3 1 6 5
1 4 9 4 9
6 6 6 4 2
matrix4 =
6 1 4 1 1
9 6 8 4 5
1 9 1 9 5
8 8 3 9 4
5 2 4 4 2
>> out
out =
3 7 5 6
3 6 6 9
1 9 2 1
6 1 1 8
8 5 6 5
Note that this whole thing would be simpler if you had simply named the contents of each .mat file with exactly the same name (e.g. matrix), instead of trying to create lots of numbered variables. Then you could simply use
S.matrix
in the loop.

More Answers (1)

Azzi Abdelmalek
Azzi Abdelmalek on 17 Jun 2016
out=[];
for k=1:100
file=sprintf('output%d',k)
M=load(file)
f=fieldnames(M)
A=M.(f)
out=[out A(:,1)]
end

Categories

Find more on Operators and Elementary Operations 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!