Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
fprintf to write array to text file

Subject: fprintf to write array to text file

From: Tim

Date: 11 Jan, 2008 08:08:03

Message: 1 of 11



Hi All,

I am trying to output a bunch of results to a text file that
will then be opened in excel.

I am finding the formating syntax strings to be largely
incomprehensible to me. The odd mystery of matlab is that
complex things are so simple and then some very simple
things seems bizarrely hard...

All I want to do is:

(1) Write some text (these will be column headers)
(2) Add the contents of a multi-column array below this
without the numbers being converted to scientific notation

Previously, I did something similar by writing the text
lines using fprintf, closing the file and then using the
"save" command to append the array data below this.
Unfortunately this converts all numbers to scientific
notation. I need the numbers to be written as simple numbers
(why does matlab make this so hard - is 1.6 really more
precise when written as 1.6000000e+000?).

%Sample Data:
savefile = 'c:\temp.txt';
result1 = 5.3;
result2 = 3.3;
result3 = 1;
mainArray = [1.2 2.3 3.4 ; 11.3 1.4 5.6 ; 1.5 2.3 10.2]

%Sample Code:
myfile = fopen(savefile ,'wt');
fprintf(myfile,'Column1\tColumn2\tColumn3\n');
fprintf(myfile, '%g\n',mainArray);
    
fclose(myfile);


--
This code doesn't work because it stacks all the columns on
top of each other. I tried moving the \t around to no avail.

The following code gets tabs after all the numbers but the
columns are still lost:
fprintf(myfile, '%g\t\n',mainArray(:,1),
'%g\t\n',mainArray(:,2));

I assume there is an easy way to stick a multi-column array
into a text file and preserve the number formatting.

Any suggestions will be greatly appreciated.

Thanks

Tim

Subject: fprintf to write array to text file

From: zhangfujian@gmail.com

Date: 11 Jan, 2008 11:01:57

Message: 2 of 11

On 1=D4=C211=C8=D5, =CF=C2=CE=E74=CA=B108=B7=D6, "Tim " <timbr...@nospamhere=
.nope> wrote:
> Hi All,
>
> I am trying to output a bunch of results to a text file that
> will then be opened in excel.
>
> I am finding the formating syntax strings to be largely
> incomprehensible to me. The odd mystery of matlab is that
> complex things are so simple and then some very simple
> things seems bizarrely hard...
>
> All I want to do is:
>
> (1) Write some text (these will be column headers)
> (2) Add the contents of a multi-column array below this
> without the numbers being converted to scientific notation
>
> Previously, I did something similar by writing the text
> lines using fprintf, closing the file and then using the
> "save" command to append the array data below this.
> Unfortunately this converts all numbers to scientific
> notation. I need the numbers to be written as simple numbers
> (why does matlab make this so hard - is 1.6 really more
> precise when written as 1.6000000e+000?).
>
> %Sample Data:
> savefile =3D 'c:\temp.txt';
> result1 =3D 5.3;
> result2 =3D 3.3;
> result3 =3D 1;
> mainArray =3D [1.2 2.3 3.4 ; 11.3 1.4 5.6 ; 1.5 2.3 10.2]
>
> %Sample Code:
> myfile =3D fopen(savefile ,'wt');
> fprintf(myfile,'Column1\tColumn2\tColumn3\n');
> fprintf(myfile, '%g\n',mainArray);
>
> fclose(myfile);
>
> --
> This code doesn't work because it stacks all the columns on
> top of each other. I tried moving the \t around to no avail.
>
> The following code gets tabs after all the numbers but the
> columns are still lost:
> fprintf(myfile, '%g\t\n',mainArray(:,1),
> '%g\t\n',mainArray(:,2));
>
> I assume there is an easy way to stick a multi-column array
> into a text file and preserve the number formatting.
>
> Any suggestions will be greatly appreciated.
>
> Thanks
>
> Tim

A for loop may be is useful for your problem.
Try something like this. It works.

savefile =3D 'temp.txt';
result1 =3D 5.3;
result2 =3D 3.3;
result3 =3D 1;
mainArray =3D [1.2 2.3 3.4 ; 11.3 1.4 5.6 ; 1.5 2.3 10.2]


%Sample Code:
myfile =3D fopen(savefile ,'wt');
fprintf(myfile,'Column1\tColumn2\tColumn3\n');
for i=3D1:3
    fprintf(myfile, '%g\t%g\t%g\n',mainArray(i,:));
end

fclose(myfile);

Subject: fprintf to write array to text file

From: Tim

Date: 11 Jan, 2008 18:04:02

Message: 3 of 11

zhangfujian wrote in message
> A for loop may be is useful for your problem.
> Try something like this. It works.
>
> savefile = 'temp.txt';
> result1 = 5.3;
> result2 = 3.3;
> result3 = 1;
> mainArray = [1.2 2.3 3.4 ; 11.3 1.4 5.6 ; 1.5 2.3 10.2]
>
>
> %Sample Code:
> myfile =fopen(savefile ,'wt');
> fprintf(myfile,'Column1\tColumn2\tColumn3\n');
> for i=1:3
> fprintf(myfile, '%g\t%g\t%g\n',mainArray(i,:));
> end
>
> fclose(myfile);

Hi,

Thanks for your suggestion. I will implement it that way.
And tha

Just to clarify how the formatting strings work (now that
you've reminded me)...
You put the whole formatting string in quotes, where the
specific strings for each column of data are designated by a
"%" as in: '%g\t%g\t%g\n' That formats the three columns of
data and separates them by tabs with a carriage return at
then end. Is that the basic format?

Two more questions...
(1) So there is really no other way to add a whole array to
a text file?
It seems hard to believe that's the best the matlab folks
can offer to get reasonably formatted data into a text file.

(2) You can append an array to an existing file like this:
save(savefile,'mainArray', '-ASCII', '-APPEND')

But as I noted previously, this formats all numbers to
scientific notation even if they are small integers. So is
there really no way to choose what format an array of
numbers is saved in when using the SAVE command?

Thanks again,

Tim

Subject: fprintf to write array to text file

From: roberson@ibd.nrc-cnrc.gc.ca (Walter Roberson)

Date: 11 Jan, 2008 18:13:06

Message: 4 of 11

In article <fm8b2i$hhn$1@fred.mathworks.com>,
Tim <timbrown@nospamhere.nope> wrote:
>So is
>there really no way to choose what format an array of
>numbers is saved in when using the SAVE command?

doc save

-ascii Save data in 8-digit ASCII format.
-ascii -double Save data in 16-digit ASCII format


That's the limit of your choice. If you want other formats,
use other commands.
--
We regret to announce that sub-millibarn resolution bio-hyperdimensional
plasmatic space polyimaging has been delayed until the release
of Windows Vista SP2.

Subject: fprintf to write array to text file

From: roberson@ibd.nrc-cnrc.gc.ca (Walter Roberson)

Date: 11 Jan, 2008 18:16:06

Message: 5 of 11

In article <fm8b2i$hhn$1@fred.mathworks.com>,
Tim <timbrown@nospamhere.nope> wrote:
>zhangfujian wrote in message
>> A for loop may be is useful for your problem.
>> Try something like this. It works.
>>
>> savefile = 'temp.txt';
>> result1 = 5.3;
>> result2 = 3.3;
>> result3 = 1;
>> mainArray = [1.2 2.3 3.4 ; 11.3 1.4 5.6 ; 1.5 2.3 10.2]
>>
>>
>> %Sample Code:
>> fprintf(myfile, '%g\t%g\t%g\n',mainArray(i,:));

>(1) So there is really no other way to add a whole array to
>a text file?

cvswrite(), dlmwrite()

You can set the cell delimiter to be a tab or space.

dlmwrite offers a 'precision' option which can be the number
of significant digits or a format specifier string.
--
   "No one has the right to destroy another person's belief by
   demanding empirical evidence." -- Ann Landers

Subject: fprintf to write array to text file

From: Dan Hensley

Date: 11 Jan, 2008 20:44:56

Message: 6 of 11

Tim wrote:
>
> Hi All,
>
> I am trying to output a bunch of results to a text file that
> will then be opened in excel.
>
> I am finding the formating syntax strings to be largely
> incomprehensible to me. The odd mystery of matlab is that
> complex things are so simple and then some very simple
> things seems bizarrely hard...


If you knew C, you'd recognize that the fprintf formatting is identical.
So that's where it came from. And it's not terribly difficult to use
once you spend some time learning the basics of the formatting.


> All I want to do is:
>
> (1) Write some text (these will be column headers)
> (2) Add the contents of a multi-column array below this
> without the numbers being converted to scientific notation
>

> %Sample Data:
> savefile = 'c:\temp.txt';
> result1 = 5.3;
> result2 = 3.3;
> result3 = 1;
> mainArray = [1.2 2.3 3.4 ; 11.3 1.4 5.6 ; 1.5 2.3 10.2]
>

> %Sample Code:
> myfile = fopen(savefile ,'wt');
> fprintf(myfile,'Column1\tColumn2\tColumn3\n');
> fprintf(myfile, '%g\n',mainArray);

You're very close. Try this. Replace the above line with the below line:

fprintf(myfile,'%g\t%g\t%g\n',mainArray.');

Now if you want a generic solution that works with any size matrix, try
this. It expects a 2D matrix:

sa = size(mainArray);
fprintf(myfile,[repmat('%g\t',1,sa(2)-1) '%g\n'],mainArray.');


Dan

Subject: fprintf to write array to text file

From: dpb

Date: 11 Jan, 2008 21:23:20

Message: 7 of 11

Dan Hensley wrote:
> Tim wrote:
...

>> without the numbers being converted to scientific notation
...

>> fprintf(myfile, '%g\n',mainArray);
>
> You're very close. Try this. Replace the above line with the below line:
>
> fprintf(myfile,'%g\t%g\t%g\n',mainArray.');
...

To ensure the above request %d would be more certain iianm. The %g will
automagically switch its output depending on the magnitude of the item
iirc, as the G edit descriptor in Fortran (which I'm w/ Tim on; the C
printf() is an abomination and adding the matrix implementation makes
formatted i/o probably in the top two or three of the FAQ list for
Matlab I would think)...(and add a :) to the parenthetical phrase above)...

--

Subject: fprintf to write array to text file

From: Tim

Date: 14 Jan, 2008 23:06:01

Message: 8 of 11


> >(1) So there is really no other way to add a whole array to
> >a text file?
>
> cvswrite(), dlmwrite()
>
> You can set the cell delimiter to be a tab or space.
>
> dlmwrite offers a 'precision' option which can be the number
> of significant digits or a format specifier string.
> --
> "No one has the right to destroy another person's belief by
> demanding empirical evidence." -- Ann
Landers


That worked great. Thanks! BTW, is it "csvwrite()"

Subject: fprintf to write array to text file

From: Tim

Date: 14 Jan, 2008 23:32:02

Message: 9 of 11

Hi Everyone,

Thanks for all the very helpful feedback. Thought I'd post
the final code I used to solve the problem in case it is
helpful to others...

% Some data:
  myData1 = ones(3) .* rand(3);
  myData2 = ones(3) .* rand(3)

%Create a new file (filename should contain the path or it
will be saved to your current directory)

% If you want excel to open it easily, make sure your
filename ends with ".csv")
  saveFileName = 'c:\test.csv';

  myfile = fopen(saveFileName ,'wt'); %'wt' opens a new file
or overwrites an existing one


% Note that all data for separate columns should be comma
separated since this will be a csv file...

%Write in the first line:
    fprintf(myfile,['File Creator,' 'TimB\n']);


% Write in the column header names for the first array (also
comma separated):
    fprintf(myfile,['Column1,Column2,Colum3\n']);
    fclose(myfile);

% Now add the array of data:
    dlmwrite(saveFileName,myData1, '-append')

% Open the file again and add another line of column headers
(adding text with dlmwrite doesn't seem to work):
    myfile = fopen(saveFileName,'a'); % 'a' opens the
file for writing

% Write in the second line column headers
    fprintf(myfile,['\nTime,Bout Size,Bout Length\n']);
    fclose(myfile);

% Add another array of data:
    dlmwrite(saveFileName,myData2, '-append')

Subject: fprintf to write array to text file

From: edward kabanyas

Date: 6 Apr, 2012 08:19:12

Message: 10 of 11

Hi Dan;

>Now if you want a generic solution that works with any size matrix, try
>this. It expects a 2D matrix:

>sa = size(mainArray);
>fprintf(myfile,[repmat('%g\t',1,sa(2)-1) '%g\n'],mainArray.');

How to save 3D array ?

For example,

data = randn(4,3,2);

fileID = fopen('test.txt','w');
fprintf(fileID,'%12.8f\n',data);
fclose(fileID);

However, when I load it again into matlab:
>> load('test.txt');

data become 1x24 array not 4x3x2 as the original.

I need 3D data file (text) for my next analysis. Hope some suggestion, thank you

Edward



Dan Hensley <somewhere@over.there> wrote in message <JJOdncHTw__VSBranZ2dnUVZ_ryqnZ2d@comcast.com>...
> Tim wrote:
> >
> > Hi All,
> >
> > I am trying to output a bunch of results to a text file that
> > will then be opened in excel.
> >
> > I am finding the formating syntax strings to be largely
> > incomprehensible to me. The odd mystery of matlab is that
> > complex things are so simple and then some very simple
> > things seems bizarrely hard...
>
>
> If you knew C, you'd recognize that the fprintf formatting is identical.
> So that's where it came from. And it's not terribly difficult to use
> once you spend some time learning the basics of the formatting.
>
>
> > All I want to do is:
> >
> > (1) Write some text (these will be column headers)
> > (2) Add the contents of a multi-column array below this
> > without the numbers being converted to scientific notation
> >
>
> > %Sample Data:
> > savefile = 'c:\temp.txt';
> > result1 = 5.3;
> > result2 = 3.3;
> > result3 = 1;
> > mainArray = [1.2 2.3 3.4 ; 11.3 1.4 5.6 ; 1.5 2.3 10.2]
> >
>
> > %Sample Code:
> > myfile = fopen(savefile ,'wt');
> > fprintf(myfile,'Column1\tColumn2\tColumn3\n');
> > fprintf(myfile, '%g\n',mainArray);
>
> You're very close. Try this. Replace the above line with the below line:
>
> fprintf(myfile,'%g\t%g\t%g\n',mainArray.');
>
> Now if you want a generic solution that works with any size matrix, try
> this. It expects a 2D matrix:
>
> sa = size(mainArray);
> fprintf(myfile,[repmat('%g\t',1,sa(2)-1) '%g\n'],mainArray.');
>
>
> Dan

Subject: fprintf to write array to text file

From: Bruno Luong

Date: 6 Apr, 2012 11:53:31

Message: 11 of 11

"edward kabanyas" <djuky_hmi@yahoo.com> wrote in message <jlm8u0$at5$1@newscl01ah.mathworks.com>...
> Hi Dan;
>
> >Now if you want a generic solution that works with any size matrix, try
> >this. It expects a 2D matrix:
>
> >sa = size(mainArray);
> >fprintf(myfile,[repmat('%g\t',1,sa(2)-1) '%g\n'],mainArray.');
>
> How to save 3D array ?
>
> For example,
>
> data = randn(4,3,2);
>
> fileID = fopen('test.txt','w');
> fprintf(fileID,'%12.8f\n',data);
> fclose(fileID);
>
> However, when I load it again into matlab:
> >> load('test.txt');
>
> data become 1x24 array not 4x3x2 as the original.
>
> I need 3D data file (text) for my next analysis. Hope some suggestion, thank you

A text file has row and column. So guess how many dimensions it can possibly store? Unless if you use some specific marker to separate the pages, or put some size information in the header, etc...

You mentioned you want to read in fortran. So how do you intend to read in fortran? If you know the answer then do the same with Matlab.

Bruno

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us