使用 fscanf 从 matlab 格式化读取
formatted read from matlab using fscanf
我有一个格式如下的文本文件:
Row: 001, rank: 6, max: 0.2431, index: 15.
Row: 002, rank: 10, max: 0.2331, index: 1.
Row: 003, rank: 110, max: 0.2330, index: 10.
也就是说,row
字段用零填充,以便数字为三位数。字段 max
也被填充以使其具有固定长度。 rank
和 index
都没有填充。
[编辑后添加post]此外,数据前面有几行不相关的文本。无关文本的行数未知。当且仅当一行位于以下行时,该行的格式如上所示:DATA START BELOW
.
有什么方法可以使用命令读取文件
[A, count] = fscanf(fid,['what is a proper format?'],[?, numberOfRows]);
A = A';
B = A(:,[i,j,k,l]);
这样 B=[1,6,0.2431,15; 2,10,0.2331,1; 3,110,0.2330,10;];
?
我知道的一种方法是[A, count] = fscanf(fid,['%s %d, %s %d, %s %f, %s %d.'],[AnInstantNumberRelatedToTheLengthOfALine, numberOfRows]);
但是,当新字段附加到每一行时,这种方法似乎缺乏灵活性。
这是一种方法:
s = importdata('file.txt'); %// read file as cell array of strings; one line per string
s = [s{:}]; %// concatenate into a single string
ind = regexp(s, 'DATA START BELOW', 'end'); %// locate line that marks start of data
s = s(ind+1:end); %// keep only data
s = regexp(s, '-?\d+\.?\d*', 'match'); %// extract numbers as a cell array of strings
s = str2double(s); %// convert to numbers
s = reshape(s.', 4, []).'; %// reshape into four columns in row-mayor order
另一个答案:
fileID = fopen('mydata.txt');
C = textscan(fileID,'%s %f %s %f %s %f %s %f','delimiter',{',','Row:','max:','rank:','index:'});
fclose(fileID);
C = C(2:2:8);
我有一个格式如下的文本文件:
Row: 001, rank: 6, max: 0.2431, index: 15.
Row: 002, rank: 10, max: 0.2331, index: 1.
Row: 003, rank: 110, max: 0.2330, index: 10.
也就是说,row
字段用零填充,以便数字为三位数。字段 max
也被填充以使其具有固定长度。 rank
和 index
都没有填充。
[编辑后添加post]此外,数据前面有几行不相关的文本。无关文本的行数未知。当且仅当一行位于以下行时,该行的格式如上所示:DATA START BELOW
.
有什么方法可以使用命令读取文件
[A, count] = fscanf(fid,['what is a proper format?'],[?, numberOfRows]);
A = A';
B = A(:,[i,j,k,l]);
这样 B=[1,6,0.2431,15; 2,10,0.2331,1; 3,110,0.2330,10;];
?
我知道的一种方法是[A, count] = fscanf(fid,['%s %d, %s %d, %s %f, %s %d.'],[AnInstantNumberRelatedToTheLengthOfALine, numberOfRows]);
但是,当新字段附加到每一行时,这种方法似乎缺乏灵活性。
这是一种方法:
s = importdata('file.txt'); %// read file as cell array of strings; one line per string
s = [s{:}]; %// concatenate into a single string
ind = regexp(s, 'DATA START BELOW', 'end'); %// locate line that marks start of data
s = s(ind+1:end); %// keep only data
s = regexp(s, '-?\d+\.?\d*', 'match'); %// extract numbers as a cell array of strings
s = str2double(s); %// convert to numbers
s = reshape(s.', 4, []).'; %// reshape into four columns in row-mayor order
另一个答案:
fileID = fopen('mydata.txt');
C = textscan(fileID,'%s %f %s %f %s %f %s %f','delimiter',{',','Row:','max:','rank:','index:'});
fclose(fileID);
C = C(2:2:8);