MATLAB: Use Textscan or sscanf

changy text fomatssscanftextscan

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

Best Answer

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