For Programmers: Free Programming Magazines  


Home > Archive > Matlab > February 2007 > help with fprintf









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author help with fprintf
Cheetan Sharma

2007-02-27, 4:29 am

hi,

i have a cell with strings (10x1 with strings like
'Seattle'
'Chicago'
....etc.

i have a vector (10x1) with numbers
10
1
.... etc.

and i want a header to be 'the data for the cites are as follows'.
how can i use fprint to create a text file in the followinf format

the data for the cities are as follow
Seattle 10
Chicago 1
....etc.

Any help would be gratefully appreciated!!

Thank you,

cq
Jérôme

2007-02-27, 4:29 am

Hi,

City={'Seattle'
'Chicago'};

Num=[10;1];

fid=fopen('data.txt','wt');
for n=1:numel(City)
fprintf(fid,'%s %d\n',City{n},Num(n));
end
fclose(fid);

Jérôme
Cheetan Sahrma

2007-02-27, 7:19 pm

how can i add a simpel header to this file 'the data for the citeis
is as follows' ?

thank you!

cs
Jérôme

2007-02-27, 7:19 pm

City={'Seattle'
'Chicago'};

Num=[10;1];

fid=fopen('data.txt','wt');
fprintf(fid,'The data for the cities is as follows:');
for n=1:numel(City)
fprintf(fid,'%s %d\n',City{n},Num(n));
end
fclose(fid);

Jérôme
Cheetan Sahrma

2007-02-27, 7:19 pm

thank you fo ryour help. the header get's mixed with teh first line
in your solution. how can i fix that? also, what if i have a header
that is two lines?

thank you for your kind help!

cs
Cheetan Sahrma

2007-02-27, 7:19 pm

got it. thank you. (i wish the fprintf documentation was a bit more
detailed..)

cs
us

2007-02-27, 7:19 pm

Cheetan Sahrma:
<SNIP happy about a nice solution...

> wish the fprintf documentation was a bit more detailed...


just a note: <jerome>'s for-loop could be simplified in this
general form

% some data
c={
'a'
'bb'
'ccc'
'dddd'
};
n=1:4;
m=pi*n;
% the engine
% note: each ROW -> 1 LINE
cn=[c.';num2cell(n);num2cell(m)];
sprintf('city %10s rank %5d / %7.3f\n',cn{:})

us
us

2007-02-27, 7:19 pm

us:
<SNIP down to possible misunderstanding...

> % note: each ROW -> 1 LINE


% note: each ROW a var -> each COL -> 1 LINE of output

us
Jos

2007-02-28, 8:15 am

Cheetan Sahrma wrote:
>
>
> got it. thank you. (i wish the fprintf documentation was a bit more
> detailed..)
>
> cs


I agree that the help of fprintf is not so informative, but the
documentation is rather detailed:

doc fprintf

or online:
<http://www.mathworks.com/access/hel...printf.html&>;

hth
Jos
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com