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 ExchangeMatrix Indexing についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by