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

1 Ansicht (letzte 30 Tage)
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.

Antworten (1)

Guillaume
Guillaume am 28 Sep. 2017
Bearbeitet: Guillaume am 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 Kommentare
Guillaume
Guillaume am 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 am 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.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by