fscanf problem with reading txt data.

1 view (last 30 days)
fid = fopen('current.txt') %Open source file "current.txt"
NumSV = fscanf(fid, '%d') %Number of Satellites (PRN)
name = fgetl(fid)
[data, count] = fscanf(fid,'%f')
fclose(fid)
%I need to extract related information from current.txt file with using fscanf but it creates empty matrix like,
NumSV =
[]
  2 Comments
per isakson
per isakson on 16 Mar 2015
  • "with using fscanf" &nbsp Why fscan?
  • What exactly do you want to read from the file?
sermet
sermet on 16 Mar 2015
I need to determine how many PRN exist in current.txt

Sign in to comment.

Accepted Answer

Star Strider
Star Strider on 16 Mar 2015
Edited: Star Strider on 16 Mar 2015
I would use textscan.
This works:
fidi = fopen('current.txt', 'rt');
NumSV = textscan(fidi, '%s%f', 'HeaderLines',1, 'EndOfLine','\r\n', 'Whitespace',' ', 'Delimiter',':');
strings = NumSV{1};
numeric = NumSV{2};
It reads in the entire file. The individual satellites are separated by NaN values in the ‘numeric’ vector, corresponding to the ‘******** Week 806 ...’ lines.
EDIT To count the number of satellites, count the number of NaN values in the ‘numeric’ vector:
NumberOfSatellites = size(isnan(numeric), 1);
When I ran my code with your file, the result was:
NumberOfSatellites =
20
  3 Comments
Stephen23
Stephen23 on 11 Feb 2021
Edited: Stephen23 on 11 Feb 2021
"This also doesn't address the question of why fscanf would fail in the first place"
It fails for exactly the same reason that your first attempt does not work.
"This makes no sense. I have attached the file if you want to check for yourself."
I checked your file. This is what the first few lines look like:
Wavelength Intensity
1.000000000000E+3 1.400000000000E+0
1.000058651026E+3 1.350000000000E+0
1.000117302053E+3 2.300000000000E+0
1.000175953079E+3 3.100000000000E+0
1.000234604106E+3 2.800000000000E+0
... etc
Your first attempt to import the file used fscanf with '%f' format string. The fscanf documentation states that "If fscanf cannot match formatSpec to the data, it reads only the portion that matches and stops processing".
Question: what is the very first character of the file?
Answer: 'W'
Question: does 'W' match the numeric format string specified (i.e. is it recognised as being part of a number)?
Answer. no.
Question: what does the documentation say happens if the data does not match the specified format?
Answer: it stops processing (thus the empty output).
With your second attempt you read (and discard) the first line (which contains non-number characters). The rest of the file contains only numbers and whitespace, which are read exactly as documented by the '%f' format specified.
So far everything works exactly as documented and expected.
srt10
srt10 on 11 Feb 2021
Thanks for your reply. I understand now.

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!