Index out of bounds error very unusual
1 回表示 (過去 30 日間)
古いコメントを表示
Good evening my friends, i have an unusual error; if my code loads these values from file it gives me error Attempted to access head(3); index out of bounds because numel(head)=1.
If it loads other values like these it works
The txt file is like that
1 1994 1 8 3 59 27 0 15 54 11
8.9 1
9.2 1
10.2 1
12.9 1
11.4 1
10.7 1
12.4 1
8.3 1
7.7 1
2.2 6
2.0 1
etc etc
I hope you have some ideas. Thanks so much for your help!
3 件のコメント
Michael
2015 年 8 月 12 日
I had the same problem. Turns out somehow sum2str got declared as a variable. Subsequently matlab tries to access the 1st entry of the variable (which didn't exist). Hence the error.
回答 (3 件)
Walter Roberson
2014 年 2 月 12 日
The error could be further down, such as near the end of file.
Try switching to
thisline = fgetl(head);
if ~ischar(thisline); break; end %end of file
head = sscanf(thisline, '%d', 11);
if length(head) < 11
fprintf('warning: line has too few elements: |%s|', thisline);
continue;
end
Nicola
2014 年 2 月 19 日
1 件のコメント
Walter Roberson
2015 年 8 月 12 日
head=fscanf(fid,'%d',11) tells MATLAB to read 11 elements even if it requires reading multiple lines to do so. The first line of the file has 11 elements and so works, but then multiple lines get read for the next fscanf(). Reading will leave off even in the middle of a text line if that is what is needed to read 11 items, and the next fscanf() would pick up in the middle of a line if need be. At some point you are ending up at the end of file with a line which is not empty but which does not have 4 items to index.
If you have a mix of line formats that imply different data structures then you need a mix of fscanf() calls. If you do not know ahead of time which data structure a line is going to be for until you read the line and count the number of items, then you need to read the line as a string, then use sscanf() to parse the string to find out how many items are on the line and react accordingly.
Any time the line format has to be examined to determine something about how the data should be interpreted, you should be reading a line at a time use fgetl() or fgets() and examining the line.
参考
カテゴリ
Help Center および File Exchange で Data Type Identification についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!