error for Index exceeds matrix dimensions

3 views (last 30 days)
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?

Accepted Answer

Matt Fig
Matt Fig on 24 Mar 2011
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);
  1 Comment
Tian Lin
Tian Lin on 24 Mar 2011
Your idea"start at N and work back to the first element"is perfect.when I change code to
for k=length(X0):-1:1;
if X0{:,k}==0;
X0(:,k)=[];
end
end
it works! Thanks,Matt

Sign in to comment.

More Answers (1)

Andrew Newell
Andrew Newell on 24 Mar 2011
You just need to replace those round brackets by curly ones:
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
The reason is that the empty matrix is the content of the cell, not the cell itself. Note also that I got rid of the colons, which should not be in there.
EDIT: And now here is a vectorized version:
Xnum = NaN(size(X0));
idx = ~cellfun('isempty',X0);
Xnum(idx) = [X0{:}];
X0{Xnum==0} = [];

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!