Info

この質問は閉じられています。 編集または回答するには再度開いてください。

How to change elements in several arbitrary positions at the same time

1 回表示 (過去 30 日間)
Ruini Qu
Ruini Qu 2018 年 11 月 1 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
Hello, I have a matrix A=[0 0 0 0; 0 0 0 0; 0 0 0 0], which I want to change the value of some elements. I have another matrix B=[1 2; 1 3; 2 4], which shows the position of the elements I want to change in A. For example, for the first row in A, I want to change the 1st and 2nd elements from 0 to 1; for the second row in A, I want to change the 1st and 3rd elements to 1; and so on. The final result I am looking for should be C=[1 1 0 0; 1 0 1 0; 0 1 0 1]. I know I can do it with a loop. But I want faster solution. Please help. Thank you!

回答 (2 件)

Rik
Rik 2018 年 11 月 1 日
編集済み: Rik 2018 年 11 月 1 日
You can use the sub2ind function (I used the bsxfun function to generate the row numbers)
A=[0 0 0 0; 0 0 0 0; 0 0 0 0];
B=[1 2; 1 3; 2 4];
ind=sub2ind(size(A),bsxfun(@times,(1:size(B,1))',ones(1,size(B,2))),B);
C=A;C(ind)=1;
isequal(C,[1 1 0 0; 1 0 1 0; 0 1 0 1])

Matt J
Matt J 2018 年 11 月 1 日
編集済み: Matt J 2018 年 11 月 1 日
[ma,na]=size(A);
C = A + sparse([1:ma;1:ma].',B,1,ma,na)

この質問は閉じられています。

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by