Filter löschen
Filter löschen

Replacing specified elements of a matrix with elements of a vector

1 Ansicht (letzte 30 Tage)
Saeid
Saeid am 28 Jun. 2019
Kommentiert: Saeid am 28 Jun. 2019
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

Akzeptierte Antwort

Matt J
Matt J am 28 Jun. 2019
Bearbeitet: Matt J am 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)

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by