From vector to matrix reshape every ith rows for each column

I have this vector:
arr = [1; 2; 3; 1; 2; 3; 1; 2; 3; 1; 2; 3]
And would like to turn it into a 4x3 matrix looking like this:
mat = [1 1 1;...
2 2 2;...
3 3 3;...
1 1 1;...
2 2 2;...
3 3 3;...
1 1 1;...
2 2 2;...
3 3 3;...
1 1 1;...
2 2 2;...
3 3 3]
So far I achieved this by doing:
a1 = arr(1:3:end);
a2 = arr(2:3:end);
a3 = arr(3:3:end);
mat = [a1 a2 a3];
Is there a more convenient way with for instance the
reshape
function?

1 Kommentar

"And would like to turn it into a 4x3 matrix looking like this"
But what you showed is a 12x3 matrix.
So which is correct: what you wrote (4x3) or what you showed us (12x3) ?

Melden Sie sich an, um zu kommentieren.

Antworten (3)

madhan ravi
madhan ravi am 22 Nov. 2018
Bearbeitet: madhan ravi am 22 Nov. 2018
use repmat() for copying
>> arr = [1; 2; 3; 1; 2; 3; 1; 2; 3; 1; 2; 3]
mat=repmat(arr,1,3)
arr =
1
2
3
1
2
3
1
2
3
1
2
3
mat =
1 1 1
2 2 2
3 3 3
1 1 1
2 2 2
3 3 3
1 1 1
2 2 2
3 3 3
1 1 1
2 2 2
3 3 3
>>
Stephen23
Stephen23 am 22 Nov. 2018

0 Stimmen

>> mat = [arr,arr,arr]
mat =
1 1 1
2 2 2
3 3 3
1 1 1
2 2 2
3 3 3
1 1 1
2 2 2
3 3 3
1 1 1
2 2 2
3 3 3
Guillaume
Guillaume am 22 Nov. 2018
If you want to achieve what your code does instead of the result you show (see Stephen's comment):
mat = reshape(arr, 3, []).'
Otherwise, use Madhan's or Stephen's answer.

Kategorien

Mehr zu Matrices and Arrays finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 22 Nov. 2018

Beantwortet:

am 22 Nov. 2018

Community Treasure Hunt

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

Start Hunting!

Translated by