Build 2-D array with same 1-D array
26 views (last 30 days)
Show older comments
I want to build a 2-D array with the same 1-D array. To say:
1-D array: [1 2 3 4 5 6]
to build a 2-D array like [1 2 3 4 5 6; 1 2 3 4 5 6; 1 2 3 4 5 6; 1 2 3 4 5 6; ...; 1 2 3 4 5 6;]
The total number of rows is determined by me. Is there any easy functions to implement to achieve this instead of using for loop?
0 Comments
Accepted Answer
John BG
on 8 Mar 2016
hi Renuyan
yes, MATLAB has repmat
A=[1 2 3 4 5 4 6]
you set the amount of repetitions
reps=5
to replicate vertically:
repmat(A,reps,1)=
1.00 2.00 3.00 4.00 5.00 6.00
1.00 2.00 3.00 4.00 5.00 6.00
1.00 2.00 3.00 4.00 5.00 6.00
1.00 2.00 3.00 4.00 5.00 6.00
1.00 2.00 3.00 4.00 5.00 6.00
replicating horizontally:
repmat(A,1,reps)=
Columns 1 through 7
1.00 2.00 3.00 4.00 5.00 6.00 1.00
Columns 8 through 14
2.00 3.00 4.00 5.00 6.00 1.00 2.00
Columns 15 through 21
3.00 4.00 5.00 6.00 1.00 2.00 3.00
Columns 22 through 28
4.00 5.00 6.00 1.00 2.00 3.00 4.00
Columns 29 through 30
5.00 6.00
so far the answer, but in similar exercises you may find also useful the command reshape. Let's say you want to stack A, either
A'
A'=
1.00
2.00
3.00
4.00
5.00
6.00
or
reshape(A,[6,1]) =
1.00
2.00
3.00
4.00
5.00
6.00
If you find this answer of any help solving your question, please click on the thumbs-up vote link,
thanks in advance
John
More Answers (1)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!