gpt4 book ai didi

matlab - 将元素 append 到数组的最快方法是什么?

转载 作者:太空宇宙 更新时间:2023-11-03 19:34:06 25 4
gpt4 key购买 nike

这是 How to append an element to an array in MATLAB? 的后续问题该问题解决了如何将元素 append 到数组的问题。那里讨论了两种方法:

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

A(end+1) = elem;

第二种方法具有与行和列数组兼容的明显优势。

但是,这个问题是:这两种方法中哪一种最快?我的直觉告诉我第二种方法是最快的,但我想要一些支持或反对它的证据。有什么想法吗?

最佳答案

第二种方法(A(end+1) = elem)更快

根据下面的基准测试(使用 timeit benchmarking function from File 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

关于matlab - 将元素 append 到数组的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27657685/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com