Index exceeds number of array elements

2 views (last 30 days)
Hello,
Please excuse my naivety as a beginner with MATLAB but I am receiving an error message I'm struggling to get past. I am ultimately trying to plot a dataset.
for i=1:nVal
[fline,count] = fscanf (fid,'%f %f %f %f %f',5);
if (mod(i,20) == 1)
fprintf ('%6.1f %7.2f\n', fline(1), fline(2) ); % display the time and x value as a check
end
t(i) = fline(1); % load vector of time values
xm(i) = fline(2); % load vector of x readings
ym(i) = fline(3); % load vector of y readings
z1m(i) = fline(4); % load vector of z1 readings
z2m(i) = fline(5); % load vector of z2 readings
end
Unrecognized function or variable 'nVal'.
The error message that is coming up is:
Index exceeds the number of array elements. Index must not exceed 0.
Error in untitled (line 40)
fprintf ('%6.1f %7.2f\n', fline(1), fline(2) ); % display the time and x value as a check
There is of course more code before and after this and as a noobie, I wasn't sure how much would have been required to help solve this solution but this is the section that appears to be causing the error. Any help is much appreciated!

Accepted Answer

Torsten
Torsten on 19 Aug 2022
Insert
class(fline)
size(fline)
after
for i=1:nVal
[fline,count] = fscanf (fid,'%f %f %f %f %f',5);
and see what type and size the variable "fline" has that you try to output in the following command
if (mod(i,20) == 1)
fprintf ('%6.1f %7.2f\n', fline(1), fline(2) ); % display the time and x value as a check
end
  5 Comments
Walter Roberson
Walter Roberson on 19 Aug 2022
Is that within the
for i=1:nVal
loop? Because if it is, then i cannot be 0 there.
What the output is showing you is that your input is empty on that particular line.
Furthermore, fscanf() with a numeric % format will skip all leading white space.
  • you might have reached end of file
  • there might be several blank lines, followed by something that is not blank but starts with something that is not numeric.
  • You might have accidentally opened the file with 'w' or 'w+' or 'a' permission instead of 'r' or 'r+' or 'a+' permission. 'w' and 'w+' would start by erasing everything in the file. 'a' (but not 'a+') would automatically position at the end of file so there might not be anything in position to read.
  • Are you looping over files? Because if so then you might have forgotten to close a previous file and open a new one
Tinman
Tinman on 19 Aug 2022
I've solved it Walter, thanks! So it appears that the actual document I was trying to read had the error which MATLAB was unable to deal with as coded which is exactly what you said. I also changed the opening of the file to 'r' which may have also helped too but with a small edit to the file trying to be read, it appears to have worked. Thank you.

Sign in to comment.

More Answers (0)

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!