error for Index exceeds matrix dimensions

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?

 채택된 답변

Matt Fig
Matt Fig 2011년 3월 24일

2 개 추천

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

Tian Lin
Tian Lin 2011년 3월 24일
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

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Andrew Newell
Andrew Newell 2011년 3월 24일

0 개 추천

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} = [];

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

질문:

2011년 3월 24일

Community Treasure Hunt

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

Start Hunting!

Translated by