How to concatenate 3D matrixes effectively/fast

1 Ansicht (letzte 30 Tage)
Hugo
Hugo am 21 Feb. 2022
Kommentiert: DGM am 21 Feb. 2022
Hi,
I have 5 matrixes, named M1,M2,M3,M4 and M5. They are all 48*1000*C, with C different in each case. I would like to concatenate M1 to M5, in dimension 3. I have written the following code:
ntables=40
nlines=1000
ncolumns1=10
ncolumns2=15
ncolumns3=20
ncolumns4=25
ncolumns5=30
M1=zeros(ntables, nlines, ncolumns1);
M2=zeros(ntables, nlines, ncolumns1);
M3=zeros(ntables, nlines, ncolumns2);
M4=zeros(ntables, nlines, ncolumns3);
M5=zeros(ntables, nlines, ncolumns4);
for i=1:nlines
dataC1(:,i,:)=cat(3,M1(:,i,:),M2(:,i,:))
dataC2(:,i,:)=cat(3,dataC1(:,i,:),M3(:,i,:))
dataC3(:,i,:)=cat(3,dataC2(:,i,:),M4(:,i,:))
dataC4(:,i,:)=cat(3,dataC3(:,i,:),M5(:,i,:))
end
The problem is that the code above is taking very long to run, like it is running for more than 1 week. Is there a faster and easier way to code this?
I thank you in advance.

Akzeptierte Antwort

DGM
DGM am 21 Feb. 2022
Bearbeitet: DGM am 21 Feb. 2022
... why not just concatenate them?
ntables=10
nlines=10
ncolumns1=10
ncolumns2=15
ncolumns3=20
ncolumns4=25
ncolumns5=30
M1=zeros(ntables, nlines, ncolumns1);
M2=zeros(ntables, nlines, ncolumns2);
M3=zeros(ntables, nlines, ncolumns3);
M4=zeros(ntables, nlines, ncolumns4);
M5=zeros(ntables, nlines, ncolumns5);
dataC = cat(3,M1,M2,M3,M4,M5);
If there's no need for M1, etc, then there's no need to concatenate at all.
ntables = 10
nlines = 10
ncolumns = [10 15 20 25 30];
dataC = zeros(ntables,nlines,sum(ncolumns));

Weitere Antworten (1)

Hugo
Hugo am 21 Feb. 2022
Hi,
Thank you for your reply. However, I am not trying to concatenate null matrixes. Instead, I am pre-allocating it. The matrixes M1....M5 are filled with values, not only 0.
  2 Kommentare
Walter Roberson
Walter Roberson am 21 Feb. 2022
Bearbeitet: Walter Roberson am 21 Feb. 2022
ntables=10;
nlines=10;
ncolumns1=10;
ncolumns2=15;
ncolumns3=20;
ncolumns4=25;
ncolumns5=30;
%now for some example data, just to illustrate that it works.
%in your real code, you would create your real M1, M2, M3, M4, M5
M1=randi(10,ntables, nlines, ncolumns1);
M2=randi(10,ntables, nlines, ncolumns2);
M3=randi(10,ntables, nlines, ncolumns3);
M4=randi(10,ntables, nlines, ncolumns4);
M5=randi(10,ntables, nlines, ncolumns5);
%The matrixes M1....M5 are filled with values, not only 0.
dataC = cat(3,M1,M2,M3,M4,M5);
whos dataC
Name Size Bytes Class Attributes dataC 10x10x100 80000 double
DGM
DGM am 21 Feb. 2022
Then the first example should suffice to concatenate them.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Produkte


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by