MATLAB: Error for Index exceeds matrix dimensions

cell arrayMATLABremoving elements

This is my code:
for k=1:length(X0); %X0 is a 1xN cell,N is an unknown number.
if X0{:,k}==0;
X0(:,k)=[]; %I want to find all 0 and delete it.
end
end
When I run these codes,there is a error:
??? Index exceeds matrix dimensions. Error in ==> Untitled3 at 36 if X0{:,k}==0;
how to change the code to make it correctly?

Best Answer

Actually, I think Tian is looking to remove the elements from the cell completely.
X0 = repmat({3 0 8 7},1,3);
X0 = X0(cellfun(@(x) ne(x,0),X0))
The reason why your loop error-ed is that you are shrinking the cell array as you go, but you told the loop to keep going until the loop index gets to the length of the original cell array. If you must do this in a loop, start at N and work back to the first element, or make a logical index that can be used after the loop is run.
for ii = length(X0):-1:1,if X0{ii}==0,X0(ii) = [];end,end
Or,
IDX = true(1,length(X0))
for ii = length(X0):-1:1,if X0{ii}==0,IDX(ii) = 0;end,end
X0 = X0(IDX);