What is the fastest way of appending an element to an array?

前端 未结 3 1636
囚心锁ツ
囚心锁ツ 2021-01-12 09:44

This is a follow-up question to How to append an element to an array in MATLAB? That question addressed how to append an element to an array. Two approaches are dis

3条回答
  •  抹茶落季
    2021-01-12 10:24

    In addition to the fast growing method pointing out above (i.e., A(k+1)), you can also get a speed increase from increasing the array size by some multiple, so that allocations become less as the size increases.

    On my laptop using R2014b, a conditional doubling of size results in about a factor of 6 speed increase:

    >> SO
    
    GATime =
        0.0288
    
    DWNTime =
        0.0048
    

    In a real application, the size of A would needed to be limited to the needed size or the unfilled results filtered out in some way.


    The Code for the SO function is below. I note that I switched to cos(k) since, for some unknown reason, there is a large difference in performance between rand() and rand(1,1) on my machine. But I don't think this affects the outcome too much.

    function [] = SO()
    
        GATime  = timeit(@GrowAlways)
        DWNTime = timeit(@DoubleWhenNeeded)
    
    end
    
    
    function [] = DoubleWhenNeeded()
    
        A     = 0;
        sizeA = 1;
        for k = 1:1E5
            if ((k+1) > sizeA)
                A(2*sizeA) = 0;
                sizeA = 2*sizeA;
            end
            A(k+1) = cos(k);
        end
    
    end
    
    function [] = GrowAlways()
    
        A     = 0;
        for k = 1:1E5
            A(k+1) = cos(k);
        end
    
    end
    

提交回复
热议问题