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 Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by