Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between append and x = [x, element]

Tags:

matlab

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!

like image 540
Giovana Morais Avatar asked Sep 09 '26 04:09

Giovana Morais


2 Answers

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).

like image 172
Cris Luengo Avatar answered Sep 12 '26 15:09

Cris Luengo


append function is a part of Symbolic Math Toolbox. It's preferred to use [X, 0] as it is part of a core language and more likely to be understood.

like image 40
Konrad Borowski Avatar answered Sep 12 '26 16:09

Konrad Borowski