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?
0 个评论
采纳的回答
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!