Updating values in array based on index vector

Hi,
I have a 2D array (with zeros), and I want to update some indexes with 1's. I have a vectors with those indexes (seperatly for X and Y).
I can do a loop for i :Array(x(i),y(i)=1. but I'm looking for something more efficient (Run time is low, but probably I can do without loops)
Doing something like Array( X; Y ) = 1; is not doing what i'm looking for.
Any suggestions?
Thanks in advance :)

 採用された回答

Mohammad Sami
Mohammad Sami 2020 年 5 月 28 日

1 投票

One of the ways is to convert your subscript to linear index and then do the assignments.
ind = sub2ind(size(A),x,y);
A(ind) = 1;

2 件のコメント

Mohammad Sami
Mohammad Sami 2020 年 5 月 28 日
A test case.
A = zeros(10,10);
x = 1:10;
y = 1:10;
ind = sub2ind(size(A),x,y);
A(ind) = 1; % set diagnol to 1
Felix
Felix 2020 年 5 月 28 日
sub2ind did the trick, Thanks!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

タグ

質問済み:

2020 年 5 月 28 日

コメント済み:

2020 年 5 月 28 日

Community Treasure Hunt

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

Start Hunting!

Translated by