In Matlab, I have a simple structure and I would like to build an array of this structure (I know how to do this). My question: is there a way to simply insert an element to that array without having to tell the array in wich position it should be? Does something similar to the "push_back" function in c++ ,that simply puts your element at the end of the vector, exists in the Matlab language?
2 Answers
You can use indexing in conjunction with end
a_struct = struct('x', 1);
a_struct(end+1) = struct('x', 2); % this writes the element to the `end+1`'th-position
disp(a_struct)
Will give you:
1x2 struct array with fields:
x
Note though, that under the hood there's no preallocation whatsoever as there might be for c++ vectors etc.
So every assignment to end+1
will internally result in making a copy of the old structure with one additional element.
See e.g. http://blogs.mathworks.com/loren/2008/02/01/structure-initialization/#7 for comments on this.

- 9,526
- 26
- 54
-
“So every assignment to end+1 will internally result in making a copy of the old structure with one additional element.” This is no longer true. See [here](https://stackoverflow.com/a/48353598/7328782) for a proof. – Cris Luengo Dec 29 '20 at 22:48
It sounds like you want to iteratively extend the array (vector). This is very inefficient in MATLAB as it will lead to a large number of reallocations as the vector grows.
In MATLAB, it is better to allocate the vector in advance (of the correct size) and index it directly, or use arrayfun to construct the array.
This is exactly the same issue as in c++'s std::vector
, where it is much better to allocate once and then use std::back_inserter
compared to push_back()
.

- 16,778
- 6
- 27
- 62
-
Ok but I don't know the vector size. But imagine have preallocated, is there a simple and clean way to just insert another element (at the end/front , I really don't care) into that vector? – karl71 Aug 12 '13 at 08:35
-
`foo(end+1)=bar;` should do the trick. But be aware that this leads to reallocation as the size of the vector changed. If you want to allocate once, you must know the correct size and use indices between `1:end`. – Marc Claesen Aug 12 '13 at 08:43
-
Can you give me a simple example of how to use "foo", I really don't understand its meaning. Thank you – karl71 Aug 12 '13 at 08:50