Fastest way to substitute elements in a matrix at given positions?

1 回表示 (過去 30 日間)
Torquato Garulli
Torquato Garulli 2019 年 10 月 15 日
コメント済み: Torquato Garulli 2019 年 10 月 16 日
Good evening,
suppose I have an array A with size (n,m) and an array B with size (n,l), with l<m.
Suppose elements of array B point to elements of array A in the following fashion:
  • B(x,y) --> A(x, B(x,y))
What is the fastest way to substitute all elements of A that are pointed by elements of B with a given value? At present I am using for loops but I guess they are not very efficient.
Also, would it be different if matrix A would be generated by repetition of the same known row n times?
Thanks a lot for any help or hint you are willing to give!!

採用された回答

Matt J
Matt J 2019 年 10 月 15 日
idx = sub2ind([n,m], repmat((1:n).',1,l) ,B);
A(idx)=value;
  5 件のコメント
Matt J
Matt J 2019 年 10 月 16 日
編集済み: Matt J 2019 年 10 月 16 日
It depends on what the code for the loop looks like. Generally speaking though, Matlab's JIT compiler can do some things to optimize M-coded for-loops, but is limited by the complexity of operations done inside the loop and your Matlab version, of course.
If you can avoid M-Coded for-loops, as my solution does, it often leads to better performance because it doesn't rely on the JIT. It is just running pre-compiled C/C++ code internally.
Torquato Garulli
Torquato Garulli 2019 年 10 月 16 日
I see!
Thanks a lot!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by