Tony
Tony

Reputation: 1393

Adding a row vector to multiple rows of a matrix, with duplicate row index

Suppose we have a matrix

A = [1,2;3,4;5,6] 
1 2
3 4
5 6

I know that matlab allows adding vector to multiple rows, for example,

A([1,2],:) = A([1,2],:) + [1,1];

then

A =
    2 3
    4 5
    5 6

However, A([1,2,1],:) + [1,1] gives the same result

A([1,2,1],:) = A([1,2,1],:) + [1,1];

then

A =
    2 3
    4 5
    5 6

This is NOT what I want. The desired effect is adding [1,1] to the first row twice, and the expected result is,

A([1,2,1],:) = A([1,2,1],:) + [1,1];

and A should be

A =
    3 4
    4 5
    5 6

How do I achieve this? thanks!

Upvotes: 2

Views: 62

Answers (1)

user6655984
user6655984

Reputation:

This can't be achieved with fancy indexing. Matlab will first evaluate the right hand side, which for A([1,2,1],:) + [1,1]; is

2 3
4 5
2 3

and then assign it to the matrix on the left. Indices are processed in order, so at first, A(1, :) gets replaced with [2 3], then A(2, :) gets replaced with [4 5], then A(1, :) gets replaced with [2 3] again (a waste of time). In no way can the newly-assigned value of A be immediately used again on the right hand side of the same assignment.

Instead, if you have to start with a list of indexes that has repetitions, the following will work:

ix = [1 2 1]
uix = unique(ix)
counts = hist(ix, uix)
A(uix, :) = A(uix, :) + counts' * [1 1]

This results in

A =    
   3   4
   4   5
   5   6

Upvotes: 2

Related Questions