- "with using fscanf"   Why fscan?
- What exactly do you want to read from the file?
fscanf problem with reading txt data.
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
per isakson
2015-3-16
采纳的回答
Star Strider
2015-3-16
编辑:Star Strider
2015-3-16
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 个评论
Stephen23
2021-2-11
编辑:Stephen23
2021-2-11
"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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!