How can I repeat a 2-D array to create a 3-D array?
29 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
Stephen23
2022 年 7 月 13 日
"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).
採用された回答
Bruno Luong
2022 年 7 月 12 日
A =[1 2 3;4 5 6];
B = repmat(reshape(A, [1 size(A)]),[5 1 1])
2 件のコメント
Bruno Luong
2022 年 7 月 13 日
編集済み: Bruno Luong
2022 年 7 月 13 日
EDIT : my deleted comment moves here
If you do repeat 3rd dimension few other approaches
A =[1 2 3;4 5 6]; N = 2;
B = repmat(A,[1,1,N]), % James's comment
B = repelem(A,1,1,N),
B = A(:,:,ones(1,N)),
B = A + zeros(1,1,N),
その他の回答 (1 件)
Voss
2022 年 7 月 12 日
% 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)
参考
カテゴリ
Help Center および File Exchange で Resizing and Reshaping Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!