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

前端 未结 3 1626
囚心锁ツ
囚心锁ツ 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条回答
  •  旧时难觅i
    2021-01-12 10:28

    The second approach (A(end+1) = elem) is faster

    According to the benchmarks below (run with the timeit benchmarking function from File Exchange), the second approach (A(end+1) = elem) is faster and should therefore be preferred.

    Interestingly, though, the performance gap between the two approaches is much narrower in older versions of MATLAB than it is in more recent versions.

    R2008a

    enter image description here

    R2013a

    benchmark run in MATLAB R2013a

    Benchmark code

    function benchmark
    
        n = logspace(2, 5, 40);
        % n = logspace(2, 4, 40); 
        tf = zeros(size(n));
        tg = tf;
    
        for k = 1 : numel(n)
            x = rand(round(n(k)), 1);
    
            f = @() append(x);
            tf(k) = timeit(f);
    
            g = @() addtoend(x);
            tg(k) = timeit(g);
        end
    
        figure
        hold on
        plot(n, tf, 'bo')
        plot(n, tg, 'ro')
        hold off
        xlabel('input size')
        ylabel('time (s)')
        leg = legend('y = [y, x(k)]', 'y(end + 1) = x(k)');
        set(leg, 'Location', 'NorthWest');
    end
    
    % Approach 1: y = [y, x(k)];
    function y = append(x)
        y = [];
        for k = 1 : numel(x);
            y = [y, x(k)];
        end
    end
    
    % Approach 2: y(end + 1) = x(k);
    function y = addtoend(x)
        y = [];
        for k = 1 : numel(x);
            y(end + 1) = x(k);
        end
    end
    

提交回复
热议问题