1

I have a matrix myVel that is of size [1 501] meaning 1 row and 501 columns. I want to extend this matrix so that the matrix will be of size [N 501], where N is an arbitrary number.

Each of the values in the columns need to be the same (meaning that all the values in the first column are all say, x and all of the values in the second column are say, y and so on). This means that each row would consist of the same values.

How can I achieve this efficiently?

MichaelGofron
  • 1,310
  • 4
  • 15
  • 29

1 Answers1

2

Divakar's solution is one way to do it, and the link he referenced shows some great ways to duplicate an array. That post, however, is asking to do it without the built-in function repmat, which is the easiest solution. Because there is no such restriction for you here, I will recommend this approach. Basically, you can use repmat to do this for you. You would keep the amount of columns the same, and you would duplicate for as many rows as you want. In other words:

myVelDup = repmat(myVel, N, 1);

Example:

myVel = [1 2 3 4 5 6];
N = 4;
myVelDup = repmat(myVel, N, 1);

Output:

>> myVel

myVel =

  1     2     3     4     5     6

>> myVelDup

myVelDup =

  1     2     3     4     5     6
  1     2     3     4     5     6
  1     2     3     4     5     6
  1     2     3     4     5     6

In general, repmat is called in the following way:

out = repmat(in, M, N);

in would be a matrix or vector of values you want duplicated, and you would want to duplicate this M times horizontally (rows) and N times vertically (columns). As such, for your case, as you have an array, you will want to duplicate this N times vertically and so we set the first parameter to N. The second parameter, the columns stay the same so we specify this to be 1 as we don't want to have any duplications... and thus the call to repmat you see above.

For more information on repmat, check out this link: http://www.mathworks.com/help/matlab/ref/repmat.html

Mahmoud Al-Qudsi
  • 28,357
  • 12
  • 85
  • 125
rayryeng
  • 102,964
  • 22
  • 184
  • 193
  • To the downvoter - I don't understand why this was downvoted when this was the solution that the OP accepted. I'm not complaining... just want to understand why this was downvoted. – rayryeng Jul 16 '14 at 21:34
  • 1
    @MahmoudAl-Qudsi - Thanks for the typo correction! – rayryeng Feb 09 '17 at 01:36