필터 지우기
필터 지우기

read numbers from mixed string

조회 수: 5 (최근 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 CenterFile Exchange에서 Low-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