Use Textscan or sscanf?

16 views (last 30 days)
John
John on 22 Aug 2013
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

Accepted Answer

Cedric
Cedric on 22 Aug 2013
Edited: Cedric on 22 Aug 2013
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 Comment
John
John on 22 Aug 2013
Thank you for your response. You have helped me out tremendously.
John

Sign in to comment.

More Answers (0)

Categories

Find more on Data Import and Export in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!