writing text files with mix of variables and strings

1 view (last 30 days)
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

Accepted Answer

Rik
Rik on 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)

More Answers (1)

Sujay C Sharma
Sujay C Sharma on 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')

Categories

Find more on Data Import and Export in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!