Adding a row vector to multiple rows of a matrix, with duplicate row index
조회 수: 27 (최근 30일)
이전 댓글 표시
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
답변 (2개)
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])]
댓글 수: 0
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]
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!