3
votes

I have a question that seems like it should have a simple answer that can avoid for loops.

Suppose I have an N x 4 array defined in MATLAB:

A = [1 2 3 4; 1 2 3 4; 1 2 3 4; 1 2 3 4; 1 2 3 4; 1 2 3 4];

In this example, N = 6, but it is arbitrary. I want to re-arrange A into a new array, B, which is 2 x 2 x N array of the form:

B(:,:,1) = [1 2; 3 4];
B(:,:,2) = [1 2; 3 4];

...

B(:,:,N) = [1 2; 3 4];

This seems like a simple problem and I tried a variety of things such as:

B = reshape(A',2,2,N);

However, this results in

B(:,:,1) = [1 3; 2 4];
B(:,:,2) = [1 3; 2 4];

...

B(:,:,N) = [1 3; 2 4];

I feel like there must be a simple way of doing this in one line using some combination of "reshape", "permute" and/or "transpose" that I am missing. Any suggestions are appreciated.

1

1 Answers

4
votes

You are only missing a final permute. This is needed because Matlab is column-major, so it fills the new array down, then across:

B = permute(reshape(A.', 2,2,N), [2 1 3]);