Eng-Tips is the largest engineering community on the Internet

Intelligent Work Forums for Engineering Professionals

  • Congratulations waross on being selected by the Eng-Tips community for having the most helpful posts in the forums last week. Way to Go!

fprintf

Status
Not open for further replies.

hoopz

Electrical
Sep 22, 2006
7
US
I'm trying to write all of the data in a matrix into a file, and I have to have a header in this file so I'm using fprintf instead of dlmwrite or something like that.

I have a matrix A, and the format I want the file to be in is:

<header>
A(1,1) A(1,2) A(1,3)
A(2,1) A(2,2) A(2,3)
etc, etc.

After I write the header, I could put A in the file by using the command:

fprintf(file, '%g %g %g\n',A);


The problem is, A is actually 707 columns wide and 353 rows long, so it's impractical for me to write '%g' 707 times. How can I do this?


Thanks
 
Replies continue below

Recommended for you

You can use this, dlmwrite(filename, M, '-append').
This way you can write your header with a seperate function and then you dlmwrite to drop the whole matrix in underneath it.

you can read more here

Hope this helps.
BsK
 
Thanks BsK, you are awesome. I should have realized you could use dlmwrite even if you had some text, it just seem kinda funny to me that I had to pound everything out with fprintf.
 
As a follow up to this I've decided to stick with fprintf. I used a 'for' loop to create a string that is 707 identifiers long, e.g. '%.16g %.16g %.16g etc. etc.'. My program took 11 seconds to run when using fprintf.

I figured using dlmwrite and '-append' would have been faster, but it turned out to be about the same speed and then I realized I hadn't specified precision. When I put 'precision','%.16g' in to my dlmwrite command, the program took 130 seconds to complete! More than ten times what it did with fprintf.

I would have thought dlmwrite would have been faster, but I'm sticking with fprintf even if it looks kinda ugly.
 
Hoopz
just curious..

What was your delimiter with dlmwrite?


How long did it take for the script to write out the identifiers?


BsK
 
The format I needed to put the data in was space-delimited, so my delimiter with dlmwrite was simply a ' '

I just used the code below to create the identifer string; there is probably a better way to do it. Still, Matlab reported the elapsed time as only 0.122 seconds, although I am on a speedy comp - 3.8 GHz P4, with 2 GB of RAM.

a = '%.16g';
for i=1:706
a= [a ' %.16g'];
end
a = [a '\n'];
 
How about this

Code:
A = rand(707,353);
a = '%.16g '; 
b = repmat(a,1,353);
b = [b '\n'];

f = fopen('test.txt','w');
fprintf(f,'%s\n', 'My header information');
fprintf(f, b, A.');

fclose(f);

M

--
Dr Michael F Platten
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top