How can I repeat a 2-D array to create a 3-D array?

조회 수: 8 (최근 30일)
Steve Francis
Steve Francis 2022년 7월 12일
댓글: Voss 2022년 7월 13일
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
Steve Francis
Steve Francis 2022년 7월 13일
Thanks again, James. You're right. Damn, I wish I'd thought about this earlier. I will spend some time seeing if I can re-write my scripts
Stephen23
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
Bruno Luong 2022년 7월 12일
A =[1 2 3;4 5 6];
B = repmat(reshape(A, [1 size(A)]),[5 1 1])
B =
B(:,:,1) = 1 4 1 4 1 4 1 4 1 4 B(:,:,2) = 2 5 2 5 2 5 2 5 2 5 B(:,:,3) = 3 6 3 6 3 6 3 6 3 6
  댓글 수: 2
Steve Francis
Steve Francis 2022년 7월 13일
편집: Steve Francis 2022년 7월 13일
Thanks very much!
Bruno Luong
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 =
B(:,:,1) = 1 2 3 4 5 6 B(:,:,2) = 1 2 3 4 5 6
B = repelem(A,1,1,N),
B =
B(:,:,1) = 1 2 3 4 5 6 B(:,:,2) = 1 2 3 4 5 6
B = A(:,:,ones(1,N)),
B =
B(:,:,1) = 1 2 3 4 5 6 B(:,:,2) = 1 2 3 4 5 6
B = A + zeros(1,1,N),
B =
B(:,:,1) = 1 2 3 4 5 6 B(:,:,2) = 1 2 3 4 5 6

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Voss
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)
ans = logical
1

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

태그

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by