read numbers from mixed string

3 ビュー (過去 30 日間)
Suresh Dahal
Suresh Dahal 2017 年 9 月 21 日
コメント済み: Walter Roberson 2017 年 9 月 21 日
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

回答 (2 件)

Simon Henin
Simon Henin 2017 年 9 月 21 日
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 件のコメント
Suresh Dahal
Suresh Dahal 2017 年 9 月 21 日
Getting an err ‘index exceeds matrix dimensions’
Walter Roberson
Walter Roberson 2017 年 9 月 21 日
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
KSSV 2017 年 9 月 21 日
str = {'xxx: 0.020000unit1' ; 'yyy: 40.537015180unit2' ;'zzz: 0.021517281unit3'} ;
x=regexp(str, '.*?(\d+(\.\d+)*)', 'tokens' ) ;
iwant = cellfun( @(x) str2double(x{1}{1}), x )

カテゴリ

Help Center および File ExchangeLow-Level File I/O についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by