Day_Dreamer
Day_Dreamer

Reputation: 3373

how can I add a vector to a matrix in matlab?

How can I add a vector to a matrix in Matlab, in a manner that the i's index of the vector would be added to all the members in the i's row?

for example:

A = [1 2 3;
     4 5 6;
     6 7 8]
v = [1;
     2;
     3]

the required result is:

[2 3 4;
 6 7 8;
 9 10 11]

Thanks a lot.

Upvotes: 3

Views: 10353

Answers (3)

mwengler
mwengler

Reputation: 2778

Just for fun:

A + v(:,[1 1 1]);

Upvotes: 8

Junuxx
Junuxx

Reputation: 14251

An alternative to bsxfun is to use repmat and repeat the column vector v as many times as A has columns:

A = [1 2 3; 4 5 6; 6 7 8];
v = [1; 2; 3]

A = A + repmat(v,1,3);

Upvotes: 6

Oli
Oli

Reputation: 16035

You can use bsxfun:

B=bsxfun(@plus,A,v);

Upvotes: 9

Related Questions