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

50 Ansichten (letzte 30 Tage)
Zheng Chen
Zheng Chen am 13 Aug. 2017
Bearbeitet: Zheng Chen am 13 Aug. 2017
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!

Antworten (2)

mizuki
mizuki am 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])]

Andrei Bobrov
Andrei Bobrov am 13 Aug. 2017
Bearbeitet: Andrei Bobrov am 13 Aug. 2017
ii = [1;2;1];
a = unique(ii);
A(a,:) = A(a,:) + accumarray(ii,1)*[1, 1]

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by