什么是追加一个元素的数组的最快方法?

编程入门 行业动态 更新时间:2024-10-26 22:28:38
本文介绍了什么是追加一个元素的数组的最快方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是一个后续问题How一个元素追加到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?

推荐答案

根据以下(与 timeit 从文件交换基准功能),第二种方法( A(结束+ 1)= ELEM )更快,应该因此是preferred。

The second approach 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

更多推荐

什么是追加一个元素的数组的最快方法?

本文发布于:2023-06-01 10:27:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/413016.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   元素   最快   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!