Effacer les filtres
Effacer les filtres

writing text files with mix of variables and strings

2 vues (au cours des 30 derniers jours)
Rae Taylor-Burns
Rae Taylor-Burns le 10 Juin 2020
Réponse apportée : Rik le 11 Juin 2020
Hi all,
I am trying to write a text file with the following code:
% Vegetation
veg_height = 1;
veg_dens = 0.5;
stem_diam = 1;
cd_factor = 1;
% Low marsh
npts = 1;
nsec = 1;
ah = 0.16 * veg_height;
bv = 0.0027 * stem_diam;
N = 312 * veg_dens;
Cd = 0.34 * cd_factor;
C = {'npts = ' [npts];
'nsec = ' [nsec];
'ah = ' [ah];
'bv = ' [bv];
'N = ' [N];
'Cd = ' [Cd]};
D = C';
fid = fopen('lowmarsh.txt','wt');
fprintf('%s' ,D{:})
fclose(fid)
What I want is a text file called lowmarsh.txt that looks like this:
npts = 1
nsec = 1
ah = 0.16
bv = 0.0027
N = 156
Cd = 0.34
But my text files are coming out empty.
Can someone please help me to figure out what I am doing wrong?
Thank you!!
Rae

Réponse acceptée

Rik
Rik le 11 Juin 2020
The reason your file is empty is that you forgot to supply the fid to the fprintf function, which causes it to print the text to the command window instead of the file.
% Vegetation
veg_height = 1;
veg_dens = 0.5;
stem_diam = 1;
cd_factor = 1;
% Low marsh
npts = 1;
nsec = 1;
ah = 0.16 * veg_height;
bv = 0.0027 * stem_diam;
N = 312 * veg_dens;
Cd = 0.34 * cd_factor;
C = {'npts = ' [npts];
'nsec = ' [nsec];
'ah = ' [ah];
'bv = ' [bv];
'N = ' [N];
'Cd = ' [Cd]};
D = C';
fid = fopen('lowmarsh.txt','wt');
fprintf(fid,'%s' ,D{:})
% ^^^^ add this
fclose(fid)

Plus de réponses (1)

Sujay C Sharma
Sujay C Sharma le 11 Juin 2020
Hi,
Have a look at the writecell function. I think using this should help you get your desired output.
Here is an example of how you can use it:
% Vegetation
veg_height = 1;
veg_dens = 0.5;
stem_diam = 1;
cd_factor = 1;
% Low marsh
npts = 1;
nsec = 1;
ah = 0.16 * veg_height;
bv = 0.0027 * stem_diam;
N = 312 * veg_dens;
Cd = 0.34 * cd_factor;
C = {'npts = ' [npts];
'nsec = ' [nsec];
'ah = ' [ah];
'bv = ' [bv];
'N = ' [N];
'Cd = ' [Cd]};
writecell(C,'lowmarsh.txt','Delimiter','tab')

Catégories

En savoir plus sur Data Import and Export dans Help Center et File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by