writing text files with mix of variables and strings

2 次查看(过去 30 天)
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

采纳的回答

Rik
Rik 2020-6-11
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)

更多回答(1 个)

Sujay C Sharma
Sujay C Sharma 2020-6-11
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')

类别

Help CenterFile Exchange 中查找有关 Data Import and Export 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by