Storing data from 2 lines of text

3 次查看(过去 30 天)
Hello there, I have this text
2.10 NAVIGATION DATA RINEX VERSION / TYPE
SPIDER V4,3,0,4633 NACLR 2013 03 13 00:04 PGM / RUN BY / DATE
2.1420D-08 7.4506D-09 -1.1921D-07 0.0000D+00 ION ALPHA
1.2288D+05 0.0000D+00 -2.6214D+05 1.9661D+05 ION BETA
4.656612873077D-09 1.687538997430D-14 503808 1731 DELTA-UTC: A0,A1,T,W
16 LEAP SECONDS
END OF HEADER
I want to store in a matrix [2 x 4] the values from line 3 and 4..I have made this function but it only works for one line (line 3):
function [ephe] = readRINEXnav()
[file,path] = uigetfile('*.**n');
fid = fopen(strcat(path,file),'r');
for tline=1:3
tline = fgets(fid);
Iono_alpha=[str2num(tline(3:13)) str2num(tline(15:25)) str2num(tline(26:37))...
str2num(tline(39:49))];
end
end
I know it is rudimentary, I'm still learning.

采纳的回答

Guillaume
Guillaume 2014-11-10
编辑:Guillaume 2014-11-10
Well, yes, you're reading the first three lines, of which the first two are mostly text only. So of course, it only works on the 3rd line.
You need to skip the first two lines before reading the next two. Two fgets or fgetl (I prefer the latter) would take care of that.
Note that I wouldn't hardcode the position of the numbers in each line as that's quite fragile. I would just detect the position of the two '*' and extract the portion of text in between. str2num can then convert all the numbers in between in one go:
%...
fid = fopen(fullfile(path, file), 'rt'); %fullfile is better than strcat, 'rt' for text file
fgetl(fid); fgetl(fid); %skip first two lines
for lcount = 1:2
tline = fgetl(fid);
starpos = find(tline == '*');
assert(numel(starpos) == 2, 'line %d does not have two *', lcount+2);
numbers{lcount} = str2num(tline(starpos(1)+1 : starpos(2)-1));
end
fclose(fid);
%...
  2 个评论
Sebastian Ciuban
Sebastian Ciuban 2014-11-10
Sorry, "*" is not part of the text file..I have edited it..
Guillaume
Guillaume 2014-11-11
编辑:Guillaume 2014-11-11
Well then, it's even simpler. You could just hardcode the start and end of the number portion of each line. Thus the inside of the loop becomes:
tline = fgetl(fid);
numbers{lcount} = str2num(tline(1:46)); %or whatever the bounds are
However, to give more flexibility, in this case I would use a regular expression to find the numeric portion of each string. I believe the following would work for you:
tline = fgetl(fid);
numpart = regexp(tline, '(?:[+-]?\d*\.?\d+(?:D[+-]\d+)? *)*', 'match', 'once');
numbers{lcount} = str2num(numpart);
Incidentally, str2num seems to be the only string to numeric conversion function in matlab to understand the D part of your strings. Neither sscanf nor str2double accept it.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by