How can I remove a value from an array but keeping an empty slot

2 views (last 30 days)
By running the following code I am able to remove the number '2'.
a = [1;2;3];
a(2) = [];
a = [1;3];
But I want my answer to be something like this.
a = [1;[];3];
The reason for this is due to I don't want to reduce the size of the array. How can this be achieved?

Accepted Answer

Stephen23
Stephen23 on 31 Jan 2017
Edited: Stephen23 on 31 Jan 2017
Method One: replace with NaN (best solution):
a = [1;2;3];
a(2) = NaN;
Method Two: store a mask:
a = [1;2;3]
mask = true(size(a));
mask(2) = false;
Method Three: use a cell array:
a = {1;2;3};
a{2} = [];
Personally I would use either one or two: they do not require moving the data in memory. Any method that actually changes the size of the array will require the array to be copied when it is changed, which is slow and unnecessary.
  1 Comment
Daniel Eidsvåg
Daniel Eidsvåg on 31 Jan 2017
I was looking into option three, but as you say it's slow and unnecessary. Method one works just fine! Thank you!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!