Significantly different time taken to index different columns of an array?

1 view (last 30 days)
When profiling my code I noticed inconsistent array indexing, as seen in the simplified version of my code below (I know that isn't the best way to sum arrays - just done to illustrate the problem). "patchIndex" is a 300 or so element cell array, where each cell consists of a nx3 array where n is a number in the order of 50000, but varies across cells. Why does it take so much longer to index the third column of the array? This happens regardless of the order in which the columns are indexed.
Cheers

Accepted Answer

James Tursa
James Tursa on 15 May 2015
Edited: James Tursa on 15 May 2015
The profiler can be a bit arbitrary sometimes when assigning timing, and this might be one of those cases. I have seen cases where 99% of the function time was assigned to the "end" statement of a for loop, which was not really helpful.
I know this is a simplified version of your real code, but you should consider moving the patchIndex{ii} part outside the inner loop, since each one of those references causes a shared data copy to be created. E.g., do it once like this:
m = numel(imageBank)
for ii = 1:m
patchIndex_ii = patchIndex{ii}; % Create the shared data copy once
n = size(patchIndex_ii,1);
for jj = 1:n
x = patchIndex_ii(jj,1);
y = patchIndex_ii(jj,2);
z = patchIndex_ii(jj,3);
s = x + y + z;
end
end
  1 Comment
Ben M
Ben M on 19 May 2015
Thanks James. I tried your suggestion and it improved the run time and the profiler no longer assigns weird timing to the different instructions.
Cheers.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!