3

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!

2 Answers2

7

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

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
1

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.

Konrad Borowski
  • 11,584
  • 3
  • 57
  • 71