How do I turn a maxtrix to a vector

1 次查看(过去 30 天)
So I have the following 167x6 matrix:
A B C D E F
G H I J K L
M N O P …
and so on to make a 167x6. I want it to look like (1x1002):
A B C D E F G H I J K L M N O P …
however, when I use reshape, it gives me this:
A G M B H N C I O D J P E K …
It sorts it by columns instead of rows. Please help
  2 个评论
Jan
Jan 2018-6-5
I've formatted the code for you today. Please use the "{} Code" button in the future.
Greg Smith
Greg Smith 2018-6-5
Thank you. Sorry, I'm brand new to this.

请先登录,再进行评论。

回答(2 个)

John D'Errico
John D'Errico 2018-6-5
编辑:John D'Errico 2018-6-5
So, you cannot use reshape in a different way? Suppose you first transpose the matrix, and THEN used reshape? (Hint.)
The point is, MATLAB stores data in a matrix going down the columns in memory. So, IF you transpose the matrix first, reshape will give you what you are looking to do.
  6 个评论
Jan
Jan 2018-6-5
@Greg: No need for apologies. This is a forum for Matlab questions. You do have Matlab questions. Then the members of the forum post answers.

请先登录,再进行评论。


Jan
Jan 2018-6-5
编辑:Jan 2018-6-5
All resorting of arrays, which keeps the neighborhood in a specific dimension, can be performed by
Y = reshape(permute(reshape(X, dim1), order2), dim3)
All you have to find is the correct definitions of the parameters. For 2D arrays, permute(T, [2,1]) can be replaced by a transpose. In some cases one or both reshapes can be omitted.
In your case:
S = ['A' 'B' 'C' 'E' 'F'; ...
'G' 'H' 'I' 'K' 'L'; ...
'M' 'N' 'O' 'P' 'Q'];
T = reshape(S.', 1, [])
PS. Inserting the quotes to produce running codes took the most time while typing this answer. Please post the data such, that they can be used by copy&paste. This is cuter than leaving the tedious work for the ones who answer.
  3 个评论
Jan
Jan 2018-6-5
C = reshape(B, [6:167,1,1002]);
This tries to reshape the elements of B to an array with the dimensions
[6,7,8,9,10,...,166,167,1,1002]
This would be huge.
You mean:
C = reshape(B, 1, 1002)
or
C = reshape(B, [1, 1002])
Another solution would be:
C = B(:).'
or the automatic determination of the needed value:
C = reshape(B, 1, [])
% ^ replaced automatically by 1002
Stephen23
Stephen23 2018-6-5
编辑:Stephen23 2018-6-5
@Greg Smith: because you specified the dimensions incorrectly. You specified the output size like this:
>> [6:167,1,1002]
ans =
6 7 8 9 10 11 ... lots of numbers here ... 166 167 1 1002
That is a really big array, with size 6x7x8x9x10x11x...x166x167x1x1002. In fact that array would have many more elements in it than there are particles in the observable universe:
>> prod([6:167,1,1002])
ans = 1.2555e+301
You probably meant to specify the size like this:
[1,1002]

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by