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

27 visualizaciones (últimos 30 días)
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!

Respuestas (2)

mizuki
mizuki el 13 de Ag. de 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 el 13 de Ag. de 2017
Editada: Andrei Bobrov el 13 de Ag. de 2017
ii = [1;2;1];
a = unique(ii);
A(a,:) = A(a,:) + accumarray(ii,1)*[1, 1]

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by