read numbers from mixed string

2 views (last 30 days)
Suresh Dahal
Suresh Dahal on 21 Sep 2017
Commented: Walter Roberson on 21 Sep 2017
hi, I want to read numbers from mixed string and write into a file. I've been trying to do so but cant get it to work. my data file has three variables with values in it like
% xxx: 0.020000unit1
% yyy: 40.537015180unit2
% zzz: 0.021517281unit3
%----------------------
%data continues with ---- break
&=%----------------------
%following code is for only one variable which obviously isn't working
clc
clear all
fid1=fopen('newdata.txt','r')
fid2=fopen('newdata1.txt','w')
% save data into a new file
while ~feof(fid1)
line=fgets(fid1)
A=sscanf(line,'xxx: %funit1\n')
fprintf(fid2,'%f',line)
end
fclose(fid1)
fclose(fid2)
%fclose all

Answers (2)

Simon Henin
Simon Henin on 21 Sep 2017
You need to print the variable A (not "line") to the newdata1 file. Also a quick modification will allow it to work on all the variables (xxx,yyy,zzz):
fid1=fopen('newdata.txt','r')
fid2=fopen('newdata1.txt','w')
% save data into a new file
while ~feof(fid1)
line=fgets(fid1)
A=sscanf(line,[line(1:3) ': %funit1\n'])
fprintf(fid2,'%f\n',A)
end
fclose(fid1)
fclose(fid2)
  2 Comments
Suresh Dahal
Suresh Dahal on 21 Sep 2017
Getting an err ‘index exceeds matrix dimensions’
Walter Roberson
Walter Roberson on 21 Sep 2017
fid1=fopen('newdata.txt','r')
fid2=fopen('newdata1.txt','w')
% save data into a new file
while ~feof(fid1)
line=fgets(fid1)
if length(line) >= 10
A=sscanf(line,[line(1:3) ': %funit1\n']);
if ~isempty(A)
fprintf(fid2,'%f\n',A);
end
end
end
fclose(fid1)
fclose(fid2)

Sign in to comment.


KSSV
KSSV on 21 Sep 2017
str = {'xxx: 0.020000unit1' ; 'yyy: 40.537015180unit2' ;'zzz: 0.021517281unit3'} ;
x=regexp(str, '.*?(\d+(\.\d+)*)', 'tokens' ) ;
iwant = cellfun( @(x) str2double(x{1}{1}), x )

Community Treasure Hunt

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

Start Hunting!