Removing Elements from Cell Array

2 views (last 30 days)
Ajay
Ajay on 4 Mar 2013
Hello, I have a cell array with some differently sized arrays of numbers in some code . This cell array gets Modified in a loop , so the first iteration looks like this :-
a{1}=[6 7];
a{2}=[4 7];
a{3}=[1 9];
a{4}=[1 19];
a{5}=[7 23];
There are some cells which need to disappear. for eg in the next iteration of the loop I want indexes {4} and {5} to go and the cell dimension reduced.
So it becomes this way
a{1}=[6 7];
a{2}=[4 7];
a{3}=[1 9];
Assume that indexes 4 and 5 need to go, I store it in an array temp
temp = [ 4 5];
Then I wrote this code:-
for i=1:size(temp,2)
a{temp(:,i)}={};
end
This is not producing the desired result ,as the cell a still records {4} and {5} as {}. I want the cell to shrink, like how it is done for rectangular arrays if we give command a(4,:)=[] and a(5,:)=[] , the array a reduces in size.
Is it possible to do that for a cell ??

Answers (2)

Azzi Abdelmalek
Azzi Abdelmalek on 4 Mar 2013
Edited: Azzi Abdelmalek on 4 Mar 2013
a={[6 7],[4 7],[1 9],[1 19],[7 23]};
temp = [ 4 5];
a(temp)=[]
  1 Comment
Jan
Jan on 4 Mar 2013
@Ajay: Please note, that Azzi does this in a vectorized form. When you use a FOR loop, removing the 4th cell element will move all subsequent elements to the front, such that removing the cell elements 4 and 5 requires:
a(4) = [];
a(4) = []; % Not a(5)!

Sign in to comment.


Ajay
Ajay on 5 Mar 2013
Edited: Ajay on 5 Mar 2013
Thank you for the answer.
So what I understand is that in cell arrays, if you want to access individual elements you could do so by using the flower brackets a{1}, a{2} etc
But when you want to access a vector of indexes it is exactly the same way as you would do for vectors,
in the sense a{2} accesses the contents of the cell whereas a(2) access the cell itself so if you enter a command a(2) =[] it initalises the cell to nothing, (or basically deletes that cell), while a{2} initialises the cell contents to nothing, so the cell is still intact. Is this correct ?

Products

Community Treasure Hunt

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

Start Hunting!