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

1 vue (au cours des 30 derniers jours)
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.

Réponses (1)

Guillaume
Guillaume le 28 Sep 2017
Modifié(e) : Guillaume le 28 Sep 2017
[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 commentaires
Guillaume
Guillaume le 28 Sep 2017
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 le 28 Sep 2017
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.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by