reshape matrix with variable length to vector

9 ビュー (過去 30 日間)
Houssam
Houssam 2021 年 6 月 17 日
コメント済み: Atsushi Ueno 2021 年 6 月 17 日
hi matlab community
i have a matrix with variable length, i want to convert it to a vector like this
matrix = [ 1 2 3; 4 5 6; 7 8 9] to vector = [1 2 3 4 5 6 7 8 9]
i ve tried
reshape(matrix, [1, 9])
but it gives me
1 4 7 2 5 8 3 6 9
PS. i can do it with a for loop but i want to use a single line code
thanks in advance
  1 件のコメント
Atsushi Ueno
Atsushi Ueno 2021 年 6 月 17 日
This is for understanding the reasonw why.
MATLAB® and Fortran use column-major layout by default.

サインインしてコメントする。

採用された回答

Stephen23
Stephen23 2021 年 6 月 17 日
M = [1,2,3;4,5,6;7,8,9]
M = 3×3
1 2 3 4 5 6 7 8 9
V = reshape(M.',1,[])
V = 1×9
1 2 3 4 5 6 7 8 9

その他の回答 (1 件)

John D'Errico
John D'Errico 2021 年 6 月 17 日
編集済み: John D'Errico 2021 年 6 月 17 日
Look at the order the elements were returned. Do you know how the elements of a matrix are stored? DOWN THE COLUMNS. So when you reshaped the vector, it gave you the elements of column 1, then column 2, etc.
All you need to do is to TRANSPOSE THE ARRAY, BEFORE the reshape.
reshape(matrix.', [1, 9])
This has the effect of turning columns into rows, and vice versa. And that is what you need.
Understanding how the elements are stored in an array is one of the most important things you can learn as you will go forwards in MATLAB. This will help you to solve many problems.

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by