append 和 x = [x, element] 的区别 [英] Difference between append and x = [x, element]

查看:27
本文介绍了append 和 x = [x, element] 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个数组 X 作为 X = [1 2 3 4 5] 并且我想在最后插入 0

使用 X = [X, 0]X = append(X, 0) 有什么区别吗?

我没有找到任何相关信息,我不确定我是否能注意到其中的差异.

提前致谢!

解决方案

正如在另一个答案中所解释的,append 是工具箱的一部分,并非所有人都可以使用.

然而,附加到矩阵的正确方法是

X(end+1) = 0;

这比 X=[X,0] 效率高很多.不同之处在于后一种形式创建了一个新数组,并将原始数组复制到其中.另一种形式只是附加到矩阵,这通常不需要重新分配.请参阅此处查看显示差异的实验(阅读实验两部分的问题和我的回答).>

I've create an array X as X = [1 2 3 4 5] and I want to insert 0 at the end of it.

Is there any difference in using X = [X, 0] and X = append(X, 0)?

I didn't find anything about and I'm not sure if I can notice the difference.

Thanks in advance!

解决方案

As explained in the other answer, append is part of a toolbox, and not available to everyone.

The correct way to append to a matrix, however, is

X(end+1) = 0;

This is a whole lot more efficient than X=[X,0]. The difference is that this latter form creates a new array, and copies the original one into it. The other form simply appends to the matrix, which usually doesn't require reallocation. See here for an experiment that shows the difference (read the question and my answer for both parts of the experiment).

这篇关于append 和 x = [x, element] 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆