MATLAB Matrix Preallocation Slower Than Dynamic Matrix Expansion

前端 未结 1 945
Happy的楠姐
Happy的楠姐 2020-12-11 09:21

In each iteration of a loop, I am calculating a MATLAB matrix. These matrices all must be concatenated together to create one final matrix. I know the dimensions of this fi

相关标签:
1条回答
  • 2020-12-11 09:57

    I have always assumed preallocation is faster for any array size and never actually tested it. So, I did a simple test timing the population of various array sizes from 1x1x3 up to 20x20x3 using 1000 iterations by both appending and preallocation methods. Here's the code:

    arraySize = 1:20;
    numIteration = 1000;
    
    timeAppend = zeros(length(arraySize), 1);
    timePreAllocate = zeros(length(arraySize), 1);
    
    for ii = 1:length(arraySize); 
        w = [];
        tic;
        for jj = 1:numIteration
            w = [w; rand(arraySize(ii), arraySize(ii), 3)];
        end
        timeAppend(ii) = toc;
    end; 
    
    for ii = 1:length(arraySize); 
        w = zeros(arraySize(ii) * numIteration, arraySize(ii), 3);
        tic;
        for jj = 1:numIteration
            indexStart = (jj - 1) * arraySize(ii) + 1;
            indexStop = indexStart + arraySize(ii) - 1;
            w(indexStart:indexStop,:,:) = rand(arraySize(ii), arraySize(ii), 3);
        end
        timePreAllocate(ii) = toc;
    end; 
    
    figure;
    axes;
    plot(timeAppend);
    hold on;
    plot(timePreAllocate, 'r');
    legend('Append', 'Preallocate');
    

    And here are the (as expected) results: Comparison of array appending vs. preallocation

    0 讨论(0)
提交回复
热议问题