What is the fastest way to add an element to an array?

This is the next question How to add an element to an array in MATLAB? This question addresses the issue of how to add an element to an array. Two approaches are discussed here:

A = [A elem]  % for a row array
A = [A; elem] % for a column array

and

A(end+1) = elem;

The second approach has an obvious advantage in that it is compatible with both arrays of rows and columns.

However, this question is: which of the two approaches is the fastest? My intuition tells me that the second, but I would like to get some evidence or against it. Any idea?

+4
source share
3 answers

Second approach faster

( timeit Exchange), (A(end+1) = elem) .

, , MATLAB, .

R2008a

enter image description here

R2013a

benchmark run in MATLAB R2013a

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
+3

?

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

:

RStime =

30.4064

CStime =

29.1075

RFtime =

0.3318

CFtime =

0.3351

, , , 100 .

+2

, (.. A(k+1)), , .

R2014b 6 :

>> SO

GATime =
    0.0288

DWNTime =
    0.0048

A , - .


SO . , cos(k), - rand() rand(1,1). , .

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
+1
source

Source: https://habr.com/ru/post/1569051/


All Articles