stanigator
stanigator

Reputation: 10926

MATLAB: Filling a matrix with each column being the same

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?

Upvotes: 6

Views: 29714

Answers (3)

AVB
AVB

Reputation: 4024

After

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

it's either

repmat(x,[1 n])

or

x(:,ones(1,n))

Upvotes: 9

James
James

Reputation: 66834

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

Upvotes: 2

kennytm
kennytm

Reputation: 523184

(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

Upvotes: 3

Related Questions