Reputation: 253
I'm working with cell arrays in a for-loop, However I want to delete a cell at run time at specified condition, and wants the rest of loop iterations to be stable. As when delete any cell from cell arrays the loop condition should be reformatted as the iterations are changed. Any suggestions/possibilities ?
Error:
Index exceeds matrix dimensions.
Error in myCode (line 33)
if (CellArray2{jj}(ii,:) ~= 0)
My Code:
while ii<=1000
for jj=1:10
if (CellArray2{jj}(ii,:) ~= 0)
CellArray1(jj) = [];
CellArray2(jj) = [];
end
end
end
Upvotes: 0
Views: 86
Reputation: 36720
The simplest way to delete elements from a array while indexing over it, is indexing backwards:
for index=numel(MyArray):-1:1
if (condition)
MyArray(index)=[]
end
end
In case you can't iterate backwards in your case, keep track of the elements you want to delete and delete all at once:
toDelete=false(size(MyArray))
for index=1:numel(MyArray)
if (condition)
toDelete(index)=true
end
end
%deletes everything afterwards, using logical indexing
MyArray(toDelete)=[]
I assume the second solution to be faster, because data has only to be shifted once, but I did not test it.
Upvotes: 1