MATLAB: Use fprintf to write to a new file

fprintfMATLAB

How do I write the data of one file ('source.dat') to another ('result.dat') using fprintf?
I tried,
fid=fopen('source.dat')
%I then manipulate the data of fid to my liking
result=fopen('result.dat','w')
fprinf(fid, desired format here)
Why am I getting an out-of-range error?

Best Answer

...first I opened my source file via
fid=fopen('source.dat')
data=fscanf(fid, ... % get the data
fid=fclose(fid); % done w/ that file...
data=sqr(data); % do something to it
fid=fopen('results.dat','w'); % a new output file
fprintf(fid, fmt, data); % write it out
fid=fclose(fid); % close it now, too...
If you need to read and write to two (or more) files simultaneously, you must keep unique variables for them--fid1 and fid2 are popular as are things like fhi and fho (file handle in/out). If you ever do something like
fid=fopen('source.dat');
...
fid=fopen('output.dat','w');
you've just trashed the handle to source.dat and can no longer get to it--it's in limbo as it's open but your program has no valid way to communicate with it and you can't even close it cleanly other than by brute force hammer of
fclose('all')
or when Matlab itself finally closes and releases open handles.
doc fopen % and friends