Replacing specified elements of a matrix with elements of a vector

조회 수: 2 (최근 30일)
Saeid
Saeid 2019년 6월 28일
댓글: Saeid 2019년 6월 28일
Imagine a 6X6 zero matrix Z=zeros(6,6). I have a vector v=[1 2 3 4] and I want to send the elements of this vector to specified positions of of Z. The row and column positions are given by the array IJ=[2 1; 2,4; 3 5; 6,2].
IJ =
2 1
2 4
3 5
6 2
where the left column is the row numbers and the right column shows the column numbers. The result should look like this:
Z =
0 0 0 0 0 0
0 1 0 2 0 0
0 0 0 0 3 0
0 0 0 0 0 0
0 0 0 0 0 0
0 4 0 0 0 0

채택된 답변

Matt J
Matt J 2019년 6월 28일
편집: Matt J 2019년 6월 28일
[m,n]=size(Z);
Z=Z+sparse(IJ(:,1), IJ(:,2), v,m,n)
or
Z=Z+accumarray(IJ,v(:),[m,n],[],[],1)

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by