Extracting numbers from a text file
显示 更早的评论
Data below is the contents of my text file
-------------------------------------------------
* ground: orig mass = 0, new mass = 0
* pelvis: orig mass = 10.7538, new mass = 12.5323
* femur_r: orig mass = 8.54927, new mass = 9.96316
* tibia_r: orig mass = 4.67404, new mass = 5.44705
* patella_r: orig mass = 0.0919138, new mass = 0.107115
* talus_r: orig mass = 0.126069, new mass = 0.146918
* calcn_r: orig mass = 1.07225, new mass = 1.24958
* toes_r: orig mass = 0.186142, new mass = 0.216927
-------------------------------------------------------------
I want to extract the numbers from my text file. I have succeeded for the first line with the code below
fid = fopen('C:\Users\Yong Cho\Documents\OSFolder\test.txt', 'r');
tline = fgetl(fid);
Lstr1=length(tline);
str_nums='[0-9]';
str_space='\s';
ind_nums=regexp(tline,str_nums);
ind_space=regexp(tline,str_space);
mask=[ind_nums ind_space];
num_str2=1:1:Lstr1;
num_str2(mask)=[];
str3=tline;
str3(num_str2)=[]
The code above only extracts the numbers for the first line which is
0 0
But I need to do that for every line. I basically need code that repeats the code above for each line. Can anyone help me with this?
采纳的回答
更多回答(1 个)
More efficient and more robust than using regexp would be to simply use one of the file importing tools. I would recommend trying textscan:
fmt = '%s%*s%f%*s%f';
opt = {'WhiteSpace','','Delimiter',':=','CollectOutput',true};
fid = fopen('temp.txt','rt');
C = textscan(fid,fmt,opt{:});
fclose(fid);
This code outputs this:
>> C{1}
ans =
'ground'
'pelvis'
'femur_r'
'tibia_r'
'patella_r'
'talus_r'
'calcn_r'
'toes_r'
>> C{2}
ans =
0 0
10.7538 12.5323
8.5493 9.9632
4.6740 5.4470
0.0919 0.1071
0.1261 0.1469
1.0722 1.2496
0.1861 0.2169
The code was tested on this file:
类别
在 帮助中心 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!