How can I remove a value from an array but keeping an empty slot
2 views (last 30 days)
Show older comments
Daniel Eidsvåg
on 31 Jan 2017
Commented: Daniel Eidsvåg
on 31 Jan 2017
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?
0 Comments
Accepted Answer
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.
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!