MATLAB Answers

indexing takes a very long time

2 views (last 30 days)
Vinny on 7 Aug 2019
Edited: Matt J on 11 Aug 2019
i have a large multi dimentional matrix that i need to iterate pixel by pixel, lets say size(A) = [2000,2000,100];
each pixel that i iterate through i take it's neighbourhood .
btw, to my appication I have to iterate by for loop.
the problem: indexing , for example
b = A(i:i+10,i+i+10,:)
takes a very long time for some reason.
i performed timing with profiler and that line is the most expensive one (timely wise).
why is indexing such an expensive operation? is there another way to do this?


Show 5 older comments
Walter Roberson
Walter Roberson on 10 Aug 2019
Could you explain more about the reason you use a for loop? Is that an external requirement (for example it might be imposed in homework)? Does each iteration depend upon the results of the previous iteration?
If you need to process a neighborhood then conv2 or filter2 or blockproc are often useful, and for more complex cases, nlfilt can be useful.
Vinny on 11 Aug 2019
All these functions require an image (meaning: mXnX1 or mXnX3 array).
I deal with a general mXnXC array. that is the reason i need a for loop.
Vinny on 11 Aug 2019
@David Googmanson
this solution works! my code is a lot faster
thank you

Sign in to comment.

Answers (1)

Matt J
Matt J on 11 Aug 2019
Edited: Matt J on 11 Aug 2019
It takes a long time because every time you execute the line
b = A(i:i+10,i+10,:)
memory is allocated for b. Instead of iterating over image neighborhoods in Mcode, you should try to write your operations in terms of use built-in functions like convn, which can access the neighborhoods in a more economical way.


Sign in to comment.

Community Treasure Hunt

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

Start Hunting!