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!