2

I want to add a vector to just a single column of a matrix.

For example:

a = zeros(5,5);
b = ones(5,1);

I want to add such b only to the second column of a such that the resultant a is

a= [ 0 1 0 0 0;
     0 1 0 0 0;
     0 1 0 0 0;
     0 1 0 0 0;
     0 1 0 0 0;]

How can I do this? I have tried doing a+b but it adds one to all the columns.

Adriaan
  • 17,741
  • 7
  • 42
  • 75
Ojasv singh
  • 474
  • 8
  • 19

1 Answers1

3

a(:,2) = a(:,2)+b does this. Specifically, you index all rows, :, of the second column, 2, of a, and add the vector b to that. Read this post for details on various indexing methods.

rahnema1 mentioned that Python-like syntax of adding to or subtracting from an argument does not require that argument to be repeated. You can thus do:

a:(,2) += b
Adriaan
  • 17,741
  • 7
  • 42
  • 75