How do I concatenate 3D arrays from multiple .mat files?

1 回表示 (過去 30 日間)
Thaís Fernandes
Thaís Fernandes 2018 年 7 月 27 日
コメント済み: Daianne Hofig 2018 年 12 月 1 日
I have 360 archives.mat, each with a variable 'A', of size 1800x400x1. I would like to concatenate these arrays in the third dimension, ie I would like an 'A1' of size 1800x400x360. For this I tried two things: 1) I used the 'cat' command (as in the code below), but it just saved the last array:
d=dir('test/*.mat');%test is the name of my directory where these files are stored
nn=length(d);
A1=[];
for ii=1:nn
eval(['load teste/',d(ii).name])
disp(d(ii).name)
A1=cat(3,A);
end
2) I tried to use [], but it only concatenates in the first or second dimension:
d=dir('test/*.mat');
nn=length(d);
A1=[];
for ii=1:nn
eval(['load test/',d(ii).name])
disp(d(ii).name)
A1=[A1;A];
end
Anyone have any suggestions on how to solve this? Thanks.
  1 件のコメント
Stephen23
Stephen23 2018 年 8 月 22 日
編集済み: Stephen23 2018 年 8 月 22 日
Note that eval does nothing useful here at all, except to complicate the code and make debugging harder. All you need is:
load(...)
Or even better:
S = load(...)
For example:
S = load(fullfile('test',d(ii).name))

サインインしてコメントする。

採用された回答

Walter Roberson
Walter Roberson 2018 年 7 月 27 日
A1 = cat(3, A1, A);
but you could also use
A1(:,:,ii) = A;
and you could pre-allocated, like
d=dir('test/*.mat');%test is the name of my directory where these files are stored
nn=length(d);
for ii=1:nn
eval(['load teste/',d(ii).name])
disp(d(ii).name)
if ii == 1
A1 = zeros(size(A,1), size(A,2), nn);
end
A1(:, :, ii) = A;
end
However, you should avoid using eval:
projectdir = 'test';
d = dir( fullfile(projectdir, '*.mat') );
nn = length(d);
for ii=1:nn
load( fullfile(projectdir, d(ii).name) )
disp(d(ii).name)
if ii == 1
A1 = zeros(size(A,1), size(A,2), nn);
end
A1(:, :, ii) = A;
end
and you should avoid using load() without any output:
projectdir = 'test';
d = dir( fullfile(projectdir, '*.mat') );
nn = length(d);
for ii=1:nn
datastruct = load( fullfile(projectdir, d(ii).name), 'A' );
A = datastruct.A;
disp(d(ii).name)
if ii == 1
A1 = zeros(size(A,1), size(A,2), nn);
end
A1(:, :, ii) = A;
end
  7 件のコメント
Walter Roberson
Walter Roberson 2018 年 7 月 30 日
I thought that was what my code did? What changes did you have to make?
Daianne Hofig
Daianne Hofig 2018 年 12 月 1 日
I had the same problem, and his code worked super smoothly! Thank you!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by