MATLAB: Hello! I need to extract the lines which start with PG10 from this text file. Could you please help me. Thanks! I would use while loop but I am not sure how.

get lines

I rescued this from the spam quarantine. Please edit your post to make the subject line the body of the message and use a short subject, then get rid of all those numbers. Attach the file with the paper clip icon.

Best Answer

fmt=['PG10 ' repmat('%f ',1,8)];
fid=fopen('sp3data.txt');
PG10=[];
while ~feof(fid)
PG10=[PG10; cell2mat(textscan(fid,fmt,'collectoutput',1))];
end
fid=fclose(fid);
is the "quick-n-dirty" solution. It simply concatenates the next set of values onto the preceding with dynamic reallocation. Presuming there aren't a zillion PG10 records in the file, this will be quick-enough.
If there are so many that performance is slow, preallocate the array as
PG10=zeros(AVERYBIGNUMBER,8);
and populate it by keeping a counter
i=0; % initialize counter
while ~feof(fid)
i=i+1; % increment
PG10(i,:)=cell2mat(textscan(fid,fmt,'collectoutput',1));
end
fid=fclose(fid);
ADDENDUM
Per the note in comments, the above won't work as is...
fmt=['PG10 ' repmat('%f ',1,8)];
fid=fopen('sp3data.txt');
PG10=[];
while ~feof(fid)
l=fgetl(fid); % read a record
if strfind(l,'PG10')
PG10=[PG10; cell2mat(textscan(l,fmt,'collectoutput',1))];
end
end
fid=fclose(fid);