Adding a row vector to multiple rows of a matrix, with duplicate row index
27 views (last 30 days)
Show older comments
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!
0 Comments
Answers (2)
mizuki
on 13 Aug 2017
What version do you use? The results of the second and the third examples on my R2017a were:
>> A([1,2],:) + [1,1]
ans =
2 3
4 5
>> A+1
ans =
2 3
4 5
6 7
If you are using R2016a or previous version, use REPMAT as
A + repmat(1,size(A))
or with different elements for each column:
A + [repmat(1,[size(A,1) 1]) repmat(2,[size(A,1) 1])]
0 Comments
Andrei Bobrov
on 13 Aug 2017
Edited: Andrei Bobrov
on 13 Aug 2017
ii = [1;2;1];
a = unique(ii);
A(a,:) = A(a,:) + accumarray(ii,1)*[1, 1]
0 Comments
See Also
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!