Use Textscan or sscanf?

6 次查看(过去 30 天)
John
John 2013-8-22
My data :)
1 764.2981300 3 0 25 103
1 764.2981300 3 0 25 103
1 764.2981300 3 0 25 103
* Gp# 5[2,1,3,4,6] x = 51.26, y = 149.1, z = 43.3, q = 0.885 dT[ 1, 18, 24, 59] Src Amplitude = 38.3
1 764.2981300 3 0 25 103
1 764.2981300 3 0 25 103
* Gp# 5[2,1,3,4,6] x = 51.26, y = 149.1, z = 43.3, q = 0.885 dT[ 1, 18, 24, 59] Src Amplitude = 38.3
Hi all,
Thanks in advance for your help.
I am loading text files with lines similar to these. The first 3 lines (Set 1) will always have this structure (different numbers). Another set (* Gp#) will be similar to the ones shown. I used fgetl to grab each line and place it in a cell{k,1} because I do not know how many times Set 1 will appear between (* Gp#) lines.
To read the first line I have tried
jj = sscanf('%d%c%d%c%d%c%d%c%d%c%d',string), resulting in jj = ' '
Is this sscanf-able?
I thought about textscan(fid), but since the lines change randomly between one format and another, I am not sure how to do so.
Any general advice?
Regards,
John

采纳的回答

Cedric
Cedric 2013-8-22
编辑:Cedric 2013-8-22
Assuming that lines starting with a '*' are some sort of block footers, here is one way to extract data blocks:
fid = fopen('myData.txt', 'r') ;
data = {[]} ; % Init cell array and 1st block.
dId = 1 ; % Data block ID/counter.
while ~feof(fid)
line = fgetl(fid) ;
if line(1) == '*' % Block end => new block+init.
dId = dId+1 ;
data{dId} = [] ;
continue ;
end
data{dId} = [data{dId}; sscanf(line, '%f %f %f %f %f %f').'] ;
end
data(end) = [] ; % Remove last, empty block.
fclose(fid) ;
Here is another solution based on a regexp split:
data = regexp(fileread('myData.txt'), '\*.+?e = [\-\d\.]+', 'split') ;
data(end) = [] ;
for dId = 1 : numel(data)
data{dId} = reshape(sscanf(data{dId}, '%f'), 6, []).' ;
end
Running either on your example outputs:
>> data
data =
[3x6 double] [2x6 double]
>> data{1}
ans =
1.0000 764.2981 3.0000 0 25.0000 103.0000
1.0000 764.2981 3.0000 0 25.0000 103.0000
1.0000 764.2981 3.0000 0 25.0000 103.0000
>> data{2}
ans =
1.0000 764.2981 3.0000 0 25.0000 103.0000
1.0000 764.2981 3.0000 0 25.0000 103.0000
  1 个评论
John
John 2013-8-22
Thank you for your response. You have helped me out tremendously.
John

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Sources 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by