Accumarray application for rectangle submatices

Is there an elegant way to exclude the for loop from the following function using the accumarray function, for example?
function K = accum(K_size, ...
Pi0, Pi1, Pj0, Pj1, ...
Ki0, Ki1, Kj0, Kj1, ...
psf_arr, psf_ind)
K = zeros(K_size);
for s = 1 : numel(psf_ind)
K( Ki0(s) : Ki1(s), Kj0(s) : Kj1(s) ) = ...
K( Ki0(s) : Ki1(s), Kj0(s) : Kj1(s) ) + ...
psf_arr( Pi0(s) : Pi1(s), Pj0(s) : Pj1(s), psf_ind(s) );
end
end

댓글 수: 6

Rik
Rik 2021년 8월 6일
I don't immediately see a way to use a more efficient method. However, indexing takes time as well, and it might be worthwhile to convert the indices of K to linear indices, instead of re-computing them.
You should check if that actually matters for your data. It might not make a difference (or even be slower).
I find it difficult to get a complete list of pixel indexes from a list of rectangle coordinates without using the ndgrid function in a loop
This is what I meant:
ind=sub2ind(K_size,Ki0(s) : Ki1(s), Kj0(s) : Kj1(s))
K(ind) = K(ind) + ...
psf_arr( Pi0(s) : Pi1(s), Pj0(s) : Pj1(s), psf_ind(s) );
Depending on what your function is actually meant to do it might be possible to replace it with a convolution. That will not allow the same flexibility as this code, but it will massively speed up the process.
This does not exclude the use of a loop.
I need to add to a large matrix several different small rectangular matrices in the specified places. I'm not sure that this can be done with a single convolution.
Jan
Jan 2021년 8월 6일
편집: Jan 2021년 8월 6일
@Grigorii Nefedov: Please provide some input data with usual sizes. It matters, if this hould be optimized for millions of loops over small blocks or some loops over huge blocks.
It is tedious to guess, how usual inputs looks in oyur code, but you should be able to create some "meaningful" data with some calls of rand().
Do you want to get an elegenat code, or a fast one? I do not see how avoiding a loop is useful in general.
Matt J
Matt J 2021년 8월 6일
If all the rectangles were the same size, I can see how you might make it faster. Otherwise, I think the for-loop is your best bet.

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

질문:

2021년 8월 6일

댓글:

2021년 8월 6일

Community Treasure Hunt

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

Start Hunting!

Translated by