error for Index exceeds matrix dimensions
Show older comments
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
More Answers (1)
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 Matrix Indexing 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!