Converting 3D matrix to a bigger 2D matrix efficiently

조회 수: 1 (최근 30일)
seb leaf
seb leaf 2019년 10월 30일
편집: seb leaf 2019년 10월 30일
Hello,
Let's say A is a 10x10x4 matrix. A(1,1,:) = a,b,c,d
I want to convert A to B a 20x20 matrix so that: B (1:2,1:2) = [a b;c d];
Is there an efficient way to create the B matrix without using loops?
Cheers!
Edit1: I wrote A as a 10x10x4 matrix, although in reality the matrix's size is around 20 000 x 20 000 x 4.
Edit 2: I reformulated the question:
  1. A is a huge M x N x 4 matrix
Example:
A = zeros(M,N,4);
A(1,1,:) = [1 1 2 2];
A(2,1,:) = [3 3 4 4];
A(1,2,:) = [5 5 6 6];
A(2,2,:) = [7 7 8 8];
2. Convert A to a regular 2*M x 2*N matrix so that:
Example:
%Desired output:
B =
1 1 5 5 . .
2 2 6 6 . .
3 3 7 7 . .
4 4 8 8 . .
. . . .
. . . .
  댓글 수: 2
Daniel M
Daniel M 2019년 10월 30일
I don't see the transformation. What happens to elements A(2,1,:) ? What goes in B(1,3:end)?
Nicolas B.
Nicolas B. 2019년 10월 30일
Have you checked whether the function reshape() could apply to your case?

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

채택된 답변

Matt J
Matt J 2019년 10월 30일
[ma,na,~]=size(A);
B=permute(reshape(A,ma,na,2,2), [4,1,3,2]);
B=reshape(B,2*ma,2*na)
  댓글 수: 2
Walter Roberson
Walter Roberson 2019년 10월 30일
I have to admit that this is one of those times when a simple for loop can be much clearer.
seb leaf
seb leaf 2019년 10월 30일
Thank you very much! It's exactly what I wanted.

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

추가 답변 (1개)

Matt J
Matt J 2019년 10월 30일
편집: Matt J 2019년 10월 30일
Is there an efficient way to create the B matrix without using loops?
There is nothing inefficient about using loops in this case. Only 4 loop iterations are required.
B=nan(20);
[k,j]=ind2sub([2,2],1:4);
for i=1:4
B( j(i) + (0:2:end-1), k(i) + (0:2:end-1) )=A(:,:,i);
end
  댓글 수: 1
James Tursa
James Tursa 2019년 10월 30일
Also, since the values are being rearranged in memory, a deep data copy is going to be required no matter which method is used.

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by