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?

 Accepted Answer

filecontent = fileread('C:\Users\Yong Cho\Documents\OSFolder\test.txt');
values = reshape( str2double(regexp(filecontent, '\d+(\.\d+)?', 'match')), 2, []) .' ;
Note: this code does not attempt to handle negative numbers, and does not attempt to handle exponential format. It also expects that when a decimal point is present that there will be digits after that (notice the 0 is not 0. or 0.0 in the text, so whatever is producing this is not putting in decimal point for integers.)

1 Comment

Thank you so much. This was much more efficient than what I had in mind.

Sign in to comment.

More Answers (1)

Stephen23
Stephen23 on 19 Jan 2017
Edited: Stephen23 on 19 Jan 2017
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:

Categories

Asked:

on 19 Jan 2017

Edited:

on 19 Jan 2017

Community Treasure Hunt

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

Start Hunting!