- "with using fscanf"   Why fscan?
- What exactly do you want to read from the file?
fscanf problem with reading txt data.
6 ビュー (過去 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 で Low-Level File I/O についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!