Path: news.mathworks.com!newsfeed-00.mathworks.com!oleane.net!oleane!news.ecp.fr!aioe.org!not-for-mail
From: dpb <none@non.net>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Writing formatted text files when column number of the ouput
Date: Tue, 31 Jul 2007 14:05:16 -0500
Organization: Aioe.org NNTP Server
Lines: 63
Message-ID: <f8o195$j6f$1@aioe.org>
References: <f8ndon$pv1$1@fred.mathworks.com>
NNTP-Posting-Host: 1MoKIWPbdhDl8ZWEL9DgBw.user.aioe.org
Mime-Version: 1.0
Content-Type: text/plain; charset=ISO-8859-1; format=flowed
Content-Transfer-Encoding: 8bit
X-Complaints-To: abuse@aioe.org
User-Agent: Thunderbird 2.0.0.5 (Windows/20070716)
Xref: news.mathworks.com comp.soft-sys.matlab:421928


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(&#8216;test.txt&#8217;,&#8217;w&#8217;)
> fprintf=(fid, &#8216;%12.8f, %12.8f, %12.8f\r\n&#8217;, test&#8217;)
> 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
&#8220;NumOut&#8221;, e.g. NumOut=4, the output has four columns;
NumOut=8, the output has eight columns;etc.
> 
> If that&#8217;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 :) )

--