将元素附加到数组的最快方法是什么? [英] What is the fastest way of appending an element to an array?
问题描述
这是如何将元素附加到 MATLAB 中的数组? 该问题解决了如何 将元素附加到数组的问题.那里讨论了两种方法:
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 discussed there:
A = [A elem] % for a row array
A = [A; elem] % for a column array
和
A(end+1) = elem;
第二种方法有一个明显的优势,即兼容行和列数组.
The second approach has the obvious advantage of being compatible with both row and column arrays.
然而,这个问题是:这两种方法中哪一种最快?我的直觉告诉我第二种方法是,但我想要一些支持或反对的证据.有什么想法吗?
However, this question is: which of the two approaches is fastest? My intuition tells me that the second one is, but I'd like some evidence for or against that. Any idea?
推荐答案
第二种方法(A(end+1) = elem
)更快
根据以下基准(使用 timeit
来自 File Exchange 的基准测试函数),第二种方法(A(end+1) = elem
)更快,因此应该是首选.
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.
有趣的是,这两种方法之间的性能差距在旧版 MATLAB 中比在较新版本中要小得多.
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
这篇关于将元素附加到数组的最快方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!