Surstroemmingpirat
Surstroemmingpirat

Reputation: 73

Repeat row vector as matrix with different offsets in each row

I want to repeat a row vector to create a matrix, in which every row is a slightly modified version of the original vector.

For example, if I have a vector v = [10 20 30 40 50], I want every row of my matrix to be that vector, but with a random number added to every element of the vector to add some fluctuations.

My matrix should look like this:

M = [10+a 20+a 30+a 40+a 50+a; 
     10+b 20+b 30+b 40+b 50+b; 
     ... ]

Where a, b, ... are random numbers between 0 and 2, for an arbitrary number of matrix rows.

Any ideas?

Upvotes: 1

Views: 288

Answers (2)

Wolfie
Wolfie

Reputation: 30047

If you have a MATLAB version earlier than 2016b (when implicit expansion was introduced, as demonstrated in Daan's answer) then you should use bsxfun.

v = [10 20 30 40 50]; % initial row vector
offsets = rand(3,1);  % random values, add one per row (this should be a column vector)

output = bsxfun(@plus,offsets,v);

Result:

>> output =
   10.643   20.643   30.643   40.643   50.643
   10.704   20.704   30.704   40.704   50.704
   10.393   20.393   30.393   40.393   50.393

This can be more easily understood with less random inputs!

v = [10 20 30 40 50];
offsets = [1; 2; 3];

output = bsxfun(@plus,offsets,v);
>> output =
   11   21   31   41   51
   12   22   32   42   52
   13   23   33   43   53

Side note: to get an nx1 vector of random numbers between 0 and 2, use

offsets = rand(n,1)*2

Upvotes: 1

dusk
dusk

Reputation: 2019

In Matlab, you can add a column vector to a matrix. This will add the vector elements to each of the row values accordingly.

Example:

>> M = [1 2 3; 4 5 6; 7 8 9];
>> v = [1; 2; 3];
>> v + M

ans =

     2     3     4
     6     7     8
    10    11    12

Note that in your case v is a row vector, so you should transpose it first (using v.').

As Sardar Usama and Wolfie note, this method of adding is only possible since MATLAB version R2016b, for earlier versions you will need to use bsxfun:

>> % instead of `v + M`
>> bsxfun(@plus, v, M)

ans =

     2     4     6
     5     7     9
     8    10    12

Upvotes: 2

Related Questions