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

1 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by