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