Replacing specified elements of a matrix with elements of a vector

2 次查看(过去 30 天)
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 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by