16

Say I have a matrix a = [1 2 3 4 5 6];, how do I reshape it in a row-wise manner for example reshape(a, 2, 3) to yield

1 2 3 4 5 6 

rather than the default column-wise result produced by MATLAB of:

1 3 5 2 4 6 

I believe this is a trivial task which probably has an inbuilt function to achieve this. I have already implemented a function that does this perfectly... however, is there a shorter, neater and more MATLAB way? Thanks.

function y = reshape2(x, m, n) y = zeros(m, n); ix = 0; for i = 1:m for j = 1:n ix = ix + 1; y(i, j) = x(ix); end end end 

3 Answers 3

23

How about this?

reshape(a, 3, 2)'

Sign up to request clarification or add additional context in comments.

2 Comments

This solution fails for ND array. Consider a 3D array 2x3x4 a = [1:2*3*4]
This solution fails for ND array. Consider a 3D array 2x3x4 a = [1:2*3*4] Expected to be reshaped as follows, b(:,:,1) = 1 2 3 4 5 6 7 8 9 10 11 12 b(:,:,2) = 13 14 15 16 17 18 19 20 21 22 23 24
3

The general way to reshape an m*n matrix A to a p*k matrix B in a row-wise manner is:

c=reshape(A',1,m*n) B=reshape(c,k,p)' example: m=3 n=4 , p=6, q=2 A=[1 2 3 4; 5 6 7 8; 9 10 11 12] c=[1 2 3 4 5 6 7 8 9 10 11 12] B=[1 2 ; 3 4; 5 6; 7 8; 9 10; 11 12] 

Comments

2

It is indeed reshape(A',cols,rows)'

( reshape(a', 3, 2)' in your example)

2 Comments

Cheers for deleting your question just now - I had just spent 10 minutes preparing an answer. I might have been useful for someone else. (I thought it was a good question).
Oh I'll re-post the question then @MatthewTaylor

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.