Filter löschen
Filter löschen

writing text files with mix of variables and strings

2 Ansichten (letzte 30 Tage)
Rae Taylor-Burns
Rae Taylor-Burns am 10 Jun. 2020
Beantwortet: Rik am 11 Jun. 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

Akzeptierte Antwort

Rik
Rik am 11 Jun. 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)

Weitere Antworten (1)

Sujay C Sharma
Sujay C Sharma am 11 Jun. 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')

Kategorien

Mehr zu Data Import and Export finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by