How can I repeat a 2-D array to create a 3-D array?
Ältere Kommentare anzeigen
A is a 2x3 array. I want to create a 3-D 'stack' so that each layer of the 3-D stack is identical to A. I've found that the following code gives the desired result:
A =[1 2 3;4 5 6];
for j=1:5
B(j,:,:)=A;
end
disp (squeeze(B(3,:,:))) % an example showing that any layer of the 3-D array is the same as A
Is there a more elegant way to do this? I tried using repmat but couldn't get the same result.
5 Kommentare
James Tursa
am 12 Jul. 2022
It would be better to have your 2D pages in the first two dimensions. I.e., B(:,:,j) instead of B(j,:,:). That way the 2D slices are contiguous in memory, and there are many functions in MATLAB and the FEX file exchange that naturally work with "stacked" 3D arrays where the 2D slice is the first two dimensions. E.g., pagemtimes( ).
Steve Francis
am 12 Jul. 2022
James Tursa
am 12 Jul. 2022
Bearbeitet: James Tursa
am 13 Jul. 2022
Understood. But if you are stuck with this poor design, note that it will cost you in cumbersome code downstream. E.g., everytime you pull a 2D slice from the array via B(j,:,:) it will be a 1xMxN 3D array and not strictly a 2D matrix. So you will be forced to reshape it or squeeze it into a 2D matrix just to do simple 2D stuff like use it in a matrix multiply. You may be forced to add in a bunch of reshaping etc. code just to deal with this. Rewriting the function will pay dividends downstream in your code if you have access to the source code and can do it. E.g., then simple repmat and extractions work easily:
A =[1 2 3;4 5 6];
N = 3;
B = repmat(A,1,1,N)
B(:,:,2)
Steve Francis
am 13 Jul. 2022
Stephen23
am 13 Jul. 2022
"That way the 2D slices are contiguous in memory..."
which also means that James Tursa's recommended approach will be more efficient (assuming that you mostly want to access those matrices).
Akzeptierte Antwort
Weitere Antworten (1)
% what you have now:
A =[1 2 3;4 5 6];
for j=1:5
B(j,:,:)=A;
end
% another way, using repmat and permute:
B_new = repmat(permute(A,[3 1 2]),5,1);
% the result is the same:
isequal(B_new,B)
Kategorien
Mehr zu Creating and Concatenating Matrices finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!