I am trying to create a matrix that is 3 x n, with each of the columns being the same. What's the easiest way of achieving it? Concatenation?
A:
(Octave can be considered as an open source/free version of MATLAB)
octave-3.0.3:2> rowvec = [1:10]
rowvec =
1 2 3 4 5 6 7 8 9 10
octave-3.0.3:3> [rowvec; rowvec; rowvec]
ans =
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Use repmat
if the number of rows is large.
octave-3.0.3:7> repmat(rowvec, 10, 1)
ans =
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
KennyTM
2010-03-11 09:55:11
A:
Use multiplication with a 1 x 3 matrix of ones
eg, x * [1 1 1]
Edit:
In Octave:
octave-3.0.3.exe:1> x = [1;2;3;4]
x =
1
2
3
4
octave-3.0.3.exe:5> x * [1 1 1]
ans =
1 1 1
2 2 2
3 3 3
4 4 4
James
2010-03-11 09:57:40
This gives `[x x x]`.
KennyTM
2010-03-11 09:58:03
It works in Octave - see the edit
James
2010-03-11 10:07:48
@James, I think @KennyTM might mean it gives `[x x x]` (where `x` is a column vector), when the OP wants `[x; x; x]` (where `x` is a row vector, as in his answer), but the question is slightly ambiguous, hence my answer.
Ramashalanka
2010-03-11 10:12:51
Ah, I see. I guess it also depends what his input is. You could always use 'transpose' to switch between our solutions.
James
2010-03-11 10:21:40
I'd say the index-based solution is the way to go (and it's generally faster).
gnovice
2010-03-11 16:43:01