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

前端 未结 3 1607
囚心锁ツ
囚心锁ツ 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:15

    How about this?

    function somescript
    
    RStime = timeit(@RowSlow)
    CStime = timeit(@ColSlow)
    RFtime = timeit(@RowFast)
    CFtime = timeit(@ColFast)
    
    function RowSlow
    
    rng(1)
    
    A = zeros(1,2);
    for i = 1:1e5
        A = [A rand(1,1)];
    end
    
    end
    
    function ColSlow
    
    rng(1)
    
    A = zeros(2,1);
    for i = 1:1e5
        A = [A; rand(1,1)];
    end
    
    end
    
    function RowFast
    
    rng(1)
    
    A = zeros(1,2);
    for i = 1:1e5
        A(end+1) = rand(1,1);
    end
    
    end
    
    function ColFast
    
    rng(1)
    
    A = zeros(2,1);
    for i = 1:1e5
        A(end+1) = rand(1,1);
    end
    
    end
    
    end
    

    For my machine, this yields the following timings:

    RStime =
    
    30.4064
    
    CStime =
    
    29.1075
    
    RFtime =
    
    0.3318
    
    CFtime =
    
    0.3351
    

    The orientation of the vector does not seem to matter that much, but the second approach is about a factor 100 faster on my machine.

提交回复
热议问题