Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reshape MATLAB vector in Row-wise manner

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
like image 716
SleepingSpider Avatar asked May 16 '13 16:05

SleepingSpider


People also ask

How do you reshape vectors in MATLAB?

B = reshape( A , sz ) reshapes A using the size vector, sz , to define size(B) . For example, reshape(A,[2,3]) reshapes A into a 2-by-3 matrix. sz must contain at least 2 elements, and prod(sz) must be the same as numel(A) . B = reshape( A , sz1,...,szN ) reshapes A into a sz1 -by- ...

How do you reshape a matrix to a row vector?

Conversion of a Matrix into a Row Vector. This conversion can be done using reshape() function along with the Transpose operation. This reshape() function is used to reshape the specified matrix using the given size vector.

How do you flip a row vector in MATLAB?

B = fliplr( A ) returns A with its columns flipped in the left-right direction (that is, about a vertical axis). If A is a row vector, then fliplr(A) returns a vector of the same length with the order of its elements reversed.


2 Answers

How about this?

reshape(a, 3, 2)'

like image 187
fnery Avatar answered Sep 30 '22 18:09

fnery


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] 
like image 30
Mohammad Avatar answered Sep 30 '22 16:09

Mohammad