Replacing specified elements of a matrix with elements of a vector

2 views (last 30 days)
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

Accepted Answer

Matt J
Matt J on 28 Jun 2019
Edited: Matt J on 28 Jun 2019
[m,n]=size(Z);
Z=Z+sparse(IJ(:,1), IJ(:,2), v,m,n)
or
Z=Z+accumarray(IJ,v(:),[m,n],[],[],1)

More Answers (0)

Community Treasure Hunt

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

Start Hunting!