Efficiently use length of array / vector / matrix

5 views (last 30 days)
I have a script that references the lengths of a few VERY long "1 by x" arrays in a few spots. Would it be more efficient to store the lengths of these arrays as variables prior to their reference?
I am currently doing lines like this:
for i = 1:1: (length(s)) % Where s is the array ....
I am not sure if Matlab forgoes recalculating the length of an array if it notices it does not change since the last time it was calculated... Thank you in advance and I apologize for my coding ignorance :)

Accepted Answer

Walter Roberson
Walter Roberson on 14 Jun 2016
My expectation would be that it will re-check the size of the array so it would be faster to store it. This is something you could benchmark. Note that for loops calculate the endpoints once and store the endpoints internally as constants, so any cost for doing the size() is going to be amoratized over the loop.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!