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

6 次查看(过去 30 天)
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?

采纳的回答

Stephen23
Stephen23 2017-1-31
编辑:Stephen23 2017-1-31
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 个评论
Daniel Eidsvåg
Daniel Eidsvåg 2017-1-31
I was looking into option three, but as you say it's slow and unnecessary. Method one works just fine! Thank you!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by