Re: Writing formatted text files when column number of the ouput is uncertain?



stephen wrote:
I want to export some outputs by writing a formatted text file. For
example, if there are three columns in my output, I will code as follows.

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
example, the number of output depends on another variable called
“NumOut”, e.g. NumOut=4, the output has four columns;
NumOut=8, the output has eight columns;etc.

If that’s the case, how to make the code or the format flexible

so that it would automatically adjust the format to accommodate
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 :) )

--

.



Relevant Pages

  • Re: Writing formatted text files when column number of the ouput
    ... how to make the code or the format flexible ... can think of would be to create a variable holding the required format ... » s='%f '; ... printf for a repeat field for formatting functions a la Fortran. ...
    (comp.soft-sys.matlab)
  • Re: how to run programs in vice-1.21
    ... I am trying to run jumpman in commodore 64 emulation mode. ... That depends on the format of the file containing the game. ... File » Attach tape image, then type LOAD + ENTER, then RUN + ENTER. ...
    (comp.emulators.cbm)
  • Re: book format
    ... I format the pages so that it can be printed in a book form. ... Format » Document » Margins ... Choose mirror margins and specify a massive gutter. ...
    (microsoft.public.mac.office.word)