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
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- ...
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.
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.
How about this?
reshape(a, 3, 2)'
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With