필터 지우기
필터 지우기

writing text files with mix of variables and strings

조회 수: 2 (최근 30일)
Rae Taylor-Burns
Rae Taylor-Burns 2020년 6월 10일
답변: Rik 2020년 6월 11일
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