MATLAB: Significantly different time taken to index different columns of an array

cell arraysindexingprofileprofiling

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.

Best Answer

  • 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;