Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: how to read and write a portion of a file
Date: Tue, 18 Nov 2008 09:27:01 +0000 (UTC)
Organization: Pierburg GmbH
Lines: 43
Message-ID: <gfu1p5$4b0$1@fred.mathworks.com>
References: <gfcj8m$ksi$1@fred.mathworks.com> <gfo3f5$a94$1@fred.mathworks.com> <gfpq4i$mte$1@fred.mathworks.com> <gfsu3a$slj$1@fred.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: webapp-05-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1227000421 4448 172.30.248.35 (18 Nov 2008 09:27:01 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Tue, 18 Nov 2008 09:27:01 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 872224
Xref: news.mathworks.com comp.soft-sys.matlab:501370


"Zahra" <zahra.yamani@nrc.gc.ca> wrote in message <gfsu3a$slj$1@fred.mathworks.com>...
> Hi Andres,
> 
> Thanks for your suggestion. I now have written the follwoing code (with the help of readline.m from file exchange) and for the same data file the time that it takes is almost 1/10 of my original code with a for loop. [..]


Hi Zahra,
based on your latest code, I've just quickly coded what I suggested above.
Some remarks:
- consider using uigetfile and uiputfile for your input and output files
- I chose to always overwrite 'temp.dat' - if you want to append, use 'a' instead of 'w' in fopen
- unfortunately, multiple space characters are not displayed correctly in the matlab central newsreader, but I assume your "RunS1=sprintf('%6d',scan1);" assignment is correct

Please check for yourself if the execution time is improved again (what are those times btw?) As I noted, this can be further optimized for very large files with only a few lines to be extracted, but I hope this will do.
Regards
Andres


% get user input
filename= input('Enter the name of data file:');
scan1   = input('Enter the initial run number:'); 
scanEnd = input('Enter the final run number:');
% compose strings to search for
scan2=scanEnd+1;
string1='Run';
RunS1=sprintf('%6d',scan1);
searchS1=strcat(string1,RunS1);
RunS2=sprintf('%6d',scan2);
searchS2=strcat(string1,RunS2);
% open file for reading
fid=fopen(filename,'r');
totalstring = fread(fid, '*char').';
fclose(fid);
% determine string positions
startIndex = strfind(totalstring, searchS1);
stopIndex  = strfind(totalstring, searchS2)-1;
if isempty(stopIndex) %searched number may exceed final run number of the file
    stopIndex = numel(totalstring);
end
% overwrite "temp.dat" with the desired part of the file
fid = fopen('temp.dat', 'w');
fwrite(fid, totalstring(startIndex:stopIndex));
fclose(fid);