read numbers from mixed string
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
0 commentaires
Réponses (2)
Simon Henin
le 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 commentaires
Walter Roberson
le 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)
KSSV
le 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 )
0 commentaires
Voir également
Catégories
En savoir plus sur String dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!