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

50 ビュー (過去 30 日間)
Zheng Chen
Zheng Chen 2017 年 8 月 13 日
編集済み: Zheng Chen 2017 年 8 月 13 日
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!

回答 (2 件)

mizuki
mizuki 2017 年 8 月 13 日
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 2017 年 8 月 13 日
編集済み: Andrei Bobrov 2017 年 8 月 13 日
ii = [1;2;1];
a = unique(ii);
A(a,:) = A(a,:) + accumarray(ii,1)*[1, 1]

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by