how to make a 3x3 matrix a 9x1 matrix?

48 visualizzazioni (ultimi 30 giorni)
Scott
Scott il 18 Nov 2022
Commentato: dpb il 18 Nov 2022
Hey i have a matrix x=[ 1 2 3; 4 5 6; 7 8 9]; how do I make this matrix become x=[ 1;2;3;4;5;6;7;8;9];?
I've tried reshape but that prioritizes columns not rows.
thanks in advance.
  1 Commento
dpb
dpb il 18 Nov 2022
Where having expression subscripting would be nice...
>> x.'(:)
x.'(:)
Error: Invalid expression. When calling a function or indexing a variable, use parentheses. Otherwise, check for mismatched delimiters.
>>
Instead it takes two steps to not have to write the explicit reshape operation...
>> x=x.';x=x(:)
x =
1.00
2.00
3.00
4.00
5.00
6.00
7.00
8.00
9.00
>>

Accedi per commentare.

Risposte (3)

John D'Errico
John D'Errico il 18 Nov 2022
The point to the answers you have gotten is if you want it to run across columns, then you can easily convert columns into rows, and THEN use reshape. That means you need to use transpose on your matrix first.
Further, you can know this, if you understand how the elements are stored in MATLAB matrices. A matrix in MATLAB stores the elements going down each column, one at a time. Since reshape does not change the order of the elements in a matrix, then you need to do that FIRST. For example, we can see the order the elements are stored in, if we do this:
A = reshape(1:6,[3,2])
A = 3×2
1 4 2 5 3 6
As you can see, reshape taks those elements, and makes them into a 3x2 array, as I told it to do. (I made this array have 6 elements so we would be clear about what is happening.) If we now unroll this array into a vector, we will get the elements back in their original sequence.
reshape(A,[6,1])
ans = 6×1
1 2 3 4 5 6
But you want to see the elements unrolled, going across the rows.
A.'
ans = 2×3
1 2 3 4 5 6
And now if we unroll that transposed array, we get the desired result.
reshape(A.',[6,1])
ans = 6×1
1 4 2 5 3 6
Understanding MATLAB manipulations like this always comes down to understanding and visualizing how the elements are stored in an array.

Torsten
Torsten il 18 Nov 2022
x=[ 1 2 3; 4 5 6; 7 8 9];
x = reshape(x.',[9 1])
x = 9×1
1 2 3 4 5 6 7 8 9

dpb
dpb il 18 Nov 2022
Transpose first...
x=reshape(x.',[],1);

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by