开发者

Syntax of 'fprintf' command in MATLAB

I've written MATLAB code for a one dimensional advection-dispersion for a conservative contaminant as follows.

% Analysis of 1D conservative contaminant migration through porous media.
% For t=25 days.

% Parameters:
dt = 1;
dx = 10;

% Coeffecients
m = (dt/dx^2)- (dt/dx);
n = -2*dt/(dx^2);
p = dt/(dx^2)+ dt/dx;

%Initialization
for i = 1:11
    c(i)= 0.0;
    h(i)= 0.0;
end

%Initial condition
c(6)= 500.0;

%Boundary condition
for i=1:11
    c(1)=0.0;
    c(11)= 0.0;
    h(1)= 0.0;
    h(11)= 0.0;
end
for k=1:25
    for i=2:10
        h(i)= c(i+1)*m + c(i)*n +c(i-1)*p;
    end
    for i=1:11
        c(i)=h(i);
    end
end

% Writing the results to file newfile.txt
fid= fopen('newfile.txt', 'wt');
fprintf(fid,%3.3f %3.3f %3.3f %3.3f %3.3f %3.3f %3.3f %3.3f %3.3f %3.3f
%3.3f %3.3f %3.3f %3.3f %3.3f %3.3f %3.3f %3.3f %3.3f\n,h);
fclose (fid);
contour(c);

But I am stuck开发者_C百科 at the fprintf command syntax. Upon executing it, it shows that some parenthesis is missing.


You need to write the format string as string, i.e.

fprintf(fid,%3.3f %3.3f %3.3f %3.3f %3.3f %3.3f %3.3f %3.3f %3.3f %3.3f
%3.3f %3.3f %3.3f %3.3f %3.3f %3.3f %3.3f %3.3f %3.3f\n,h);

Should be

fprintf(fid,['%3.3f %3.3f %3.3f %3.3f %3.3f %3.3f %3.3f %3.3f %3.3f %3.3f',...
'%3.3f %3.3f %3.3f %3.3f %3.3f %3.3f %3.3f %3.3f %3.3f\n'],h);

The dots signify a line break, and the square brackets catenate the strings on the two lines.


Also, you're not really writing Matlab code here. For example, zour initialization

for i = 1:11
    c(i)= 0.0;
    h(i)= 0.0;
end

can be written as

c = zeros(1,11);
h = zeros(1,11);
or
[c,h] = deal(zeros(1,11));

Furthermore,

for i=1:11
    c(1)=0.0;
    c(11)= 0.0;
    h(1)= 0.0;
    h(11)= 0.0;
end

Does absolutely nothing here, since you have initialized the vectors to zeros already, and even if you wanted to keep the lines in order to be able to change values, you can eliminate the loop.

Finally,

for i=1:11
   c(i)=h(i);
end

can be rewritten as c = h;


You need quotes around your format string, like so:

fprintf(fid,'%3.3f %3.3f ... %3.3f\n',h);

(don't actually put the ... in, I've just put it there as a placeholder so I don't have to type in the lot, and to improve readability).


You've already gotten an answer explaining why you get an error. I would however write this as:

fprintf(fid,'%3.3f ',h);
fprintf(fid,'\n');

The template is re-used until all elements in h are exhausted. The newline needs to be printed separately in this case.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜