how can I select matrix values for those cols and rows for which an f(col,row)==true?

1 回表示 (過去 30 日間)
Jasper van Casteren
Jasper van Casteren 2017 年 9 月 28 日
コメント済み: Guillaume 2017 年 9 月 28 日
I have a huge matrix A (10k*10k) and I have a function that returns false/true for each combination of a row and a column number : f(row, col) = boolean. I need to do A(f(row,col)) = X;
How to do that quickly (I need to do this very often)?
I saw arrayfun and spfun but the element function does not allow for row and column arguments.

回答 (1 件)

Guillaume
Guillaume 2017 年 9 月 28 日
編集済み: Guillaume 2017 年 9 月 28 日
[rows, cols] = ndgrid(1:size(A, 1), 1:size(A, 2));
Then, if f can operate directly with pairs of matrices, simply:
A(f(rows, cols)) = X;
otherwise if f only works with scalar values:
A(arrayfun(@f, rows, cols)) = X;
  2 件のコメント
Guillaume
Guillaume 2017 年 9 月 28 日
Comment by Jasper van Casteren moved here:
thank you for this, but
[rows, cols] = ndgrid(1:size(A, 1), 1:size(A, 2));
takes more than a second, and allocates two huge matrices. Is there no more efficient way?
Guillaume
Guillaume 2017 年 9 月 28 日
Depending on how f is implemented you may get away with:
A(f((1:size(A, 1))', 1:size(A, 2))
or
A(bsxfun(@f, (1:size(A, 1))', 1:size(A, 2))
but ultimately, it's a trade-off of memory vs speed. If a loop works better for you then use that.
It's also possible that modifying the way f works may provide some / lots of / no potential for improvement.

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

カテゴリ

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