Re: Writing formatted text files when column number of the ouput is uncertain?
- From: dpb <none@xxxxxxx>
- Date: Tue, 31 Jul 2007 14:05:16 -0500
stephen wrote:
I want to export some outputs by writing a formatted text file. Forexample, if there are three columns in my output, I will code as follows.
example, the number of output depends on another variable called
fid=fopen(‘test.txt’,’w’)
fprintf=(fid, ‘%12.8f, %12.8f, %12.8f\r\n’, test’)
fclose(fid)
However, the number of the columns in the output is not certain. For
“NumOut”, e.g. NumOut=4, the output has four columns;
NumOut=8, the output has eight columns;etc.
so that it would automatically adjust the format to accommodate
If that’s the case, how to make the code or the format flexible
different numbers of column in the output when writing a formatted text
file?
[Apologies for wrapping/quoting fouled owing to long lines in original...I guess it's getting worked on... :)]
I read the exchange and as also am stuck in (apparently) the dark ages of previous version, if dlmwrite() doesn't behave as required, best I can think of would be to create a variable holding the required format string "on the fly" and use it.
Something like the following could be wrapped in a function...
» NC = 3;
» x=randn(5,3)
x =
0.1746 -0.1364 -0.8323
-0.1867 0.1139 0.2944
0.7258 1.0668 -1.3362
-0.5883 0.0593 0.7143
2.1832 -0.0956 1.6236
» s='%f ';
» f=s;for i=1:NC-1; f=cat(2,f,s);end, f=strcat(f, '\n');
» sprintf(f,x)
ans =
0.174639 -0.186709 0.725791
-0.588317 2.183186 -0.136396
0.113931 1.066768 0.059281
-0.095648 -0.832349 0.294411
-1.336182 0.714325 1.623562
»
You could include a delimiter instead of the space I used in the substring and the format desired as well for added flexibility.
It's a poor man's substitute for the (sadly) lacking facility in C printf for a repeat field for formatting functions a la Fortran.
Of course, if NC gets to be very large and the field width is sizable you may run into system record length problems.
hth...(or I didn't miss the mark of the request too far :) )
--
.
- Follow-Ups:
- References:
- Prev by Date: Re: Find nearest index
- Next by Date: Re: Generating random numbers on unit sphere
- Previous by thread: Re: Writing formatted text files when column number of the ouput is uncertain?
- Next by thread: Re: Writing formatted text files when column number of the ouput
- Index(es):
Relevant Pages
|