How do I turn a vector into a specific matrix in MATLAB (example in post)

28 Views Asked by At

I'm currently wracking my brains on how to solve this specific situation:

I have a (20x1) vector that looks like:

$$ H' = \begin{matrix}1&2&3&4&5& \dots & 19 & 20 \end{matrix} $$

I wish to turn it or reshape it into a (4x5) matrix that looks exactly like this:

$$ H_{\mathrm{new}} = \begin{matrix} 1 & 2 & 3 & 4 & 5 \\ 6 & 7 & 8 & 9 & 10\\ 11 & 12 & 13 & 14 & 15\\ 16 & 17 & 18 & 19 & 20\\ \end{matrix} $$

I have tried using the reshape() function, but it doesn't seem to be working the way I want it to. Is there a set of nested for loops I could use or some different functions to use?

Thank you!

1

There are 1 best solutions below

2
On BEST ANSWER

The reshape() function fills out the matrix by column. You could build your own nested for loops, but you could also use transpose() cleverly:

H_new = reshape(H, [5,4])’

Note that the dimensions are swapped and the is syntactic sugar for transpose().