MATLAB Answers

How to concentrate matrix 100 times?

6 views (last 30 days)
for testnum=1:100
filesavepath=['H:\Desktop\0208\' num2str(testnum) '_sen'];
load(fullfile([filesavepath '\0208_' num2str(testnum) '_sen_avg_3.mat']),'matrix_avg');
eval(sprintf('matrix_%g=matrix_avg;',testnum));
end
matrix=cat(2,matrix_1,matrix_2,matrix_3,matrix_4,matrix_5,matrix_6,matrix_7,matrix_8,matrix_9,matrix_10,matrix_11,matrix_12);
I am trying to concentrate 100 matrix for instance. I know how to load them 100 times at different folder, but how to make my last line
matrix=cat(2,matrix_1,matrix_2,.....matrix_99,matrix_100);
Thank you!

  1 Comment

Geoff Hayes
Geoff Hayes on 11 Feb 2019
Tsuwei - are all of your matrices of the same dimension? If not, then you could use a cell array to store all of these matrices.
myMatrices = cell(100,1);
for testnum=1:100
filesavepath=['H:\Desktop\0208\' num2str(testnum) '_sen'];
load(fullfile([filesavepath '\0208_' num2str(testnum) '_sen_avg_3.mat']),'matrix_avg');
myMatrices{testNum} = matrix_avg;
end
If they are all of the same dimension then you should be able to create a single matrix that is sized appropriately.
In either case, try to avoid dynamically creating matrices with eval. This can lead to errors and has been discussed elsewhere in this forum.

Sign in to comment.

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick on 11 Feb 2019
Edited: Stephen Cobeldick on 11 Feb 2019
Your approach is entirely in the wrong direction: using numbered variables is a sign that you are doing something wrong with your data/code design. Read this to know some of the reasons why:
The simpler alternative is to load the file data into an output variable (which is a structure), then your task is trivially easy (and much more efficient):
N = 100;
C = cell(1,N);
for k = 1:N
F = fullfile(...);
S = load(F,'matrix_avg');
C{k} = S.matrix_avg;
end
M = cat(2,C{:})
See also:

  0 Comments

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!