views:

219

answers:

3

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
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
This gives `[x x x]`.
KennyTM
It works in Octave - see the edit
James
@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
Ah, I see. I guess it also depends what his input is. You could always use 'transpose' to switch between our solutions.
James
+2  A: 

After

n=7
x=[1;2;3]

it's either

repmat(x,[1 n])

or

x(:,ones(1,n))
AVB
I'd say the index-based solution is the way to go (and it's generally faster).
gnovice
Thanks. repmat is the keyword that I was looking for, but forgot.
stanigator

related questions