2
votes

I have a vector with the size (1,9) with the value as follows:

 V= [0.5 0.1 0.1 0.9 0.5 0.1 0.9 0.9 0.5]

How can I convert the vector V into the matrix M with the size of (3,3) which the first row is the first 3 elements of the vector and the second row contains the next 3 elements of the vector and keeping that rule for all of other elements of the vector as follows:

       0.5 0.1 0.1
M=     0.9 0.5 0.1
       0.9 0.9 0.5

Also for different sized vectors, like for example (1,100), how can I convert into a matrix of (10,10) base on the rule above?

1

1 Answers

6
votes

Use reshape, then transpose the result:

M = reshape(V, 3, 3).';

reshape transforms a vector into a matrix of a desired size. The matrix is created in column-major order. Therefore, just using reshape by itself will place the elements in the columns. Since you desire the elements to be populated by rows, a trick is to simply transpose the result.

In general, you want to reshape a N element vector V into a square matrix M of size sqrt(N) x sqrt(N) in row-major order. You can do this for the general case:

N = sqrt(numel(V));
M = reshape(V, N, N).';

This of course assumes that the total number of elements in V is a perfect square.