Information Technology Reference
In-Depth Information
longer in use. Transfer of arrays in and out of functions is performed very efficiently
by transferring references to the arrays. 15
Transferring functions (here the right-hand side, f. u / , in the ODE u 0 .t / D f. u / )
to the heun function follows the set-up from Sect. 6.3.5 . We find it convenient to
create the u array inside the heun function. The syntax [0:n] * 0 first creates an
array with values 0 , 1 , up to and including n , and then all the elements in this array
are multiplied by zero. There is actually no need to initialize the array elements,
since this will be done in the subsequent loop. Arrays in Matlab always start with
1 as the index so we need to rewrite Algorithm 6.12 . Although this is easy (just
replace i by i C 1 ), the rewrite is often an error-prone process.
File writing in Matlab is very similar to file writing in C. The basic statements
are typically
fid = fopen('sol.dat', 'w');
fprintf(fid, 'some text, u[%d]=%g\n', i, u(i));
fclose(fid);
Here we have used an output function fprintf , which is very convenient when
we want to control the format of the output. The function follows the syntax of
the printf -family of functions originating from C. The first argument is a string,
where variables can be inserted in “slots” starting with % . The variables are listed
after the format string (here i and u(i) ). The character after % determines the for-
matting of integers, reals, or strings. Here we specify that an integer and a real are
to be written as compactly as possible: %d and %g , respectively. More sophisticated
formatting, e.g., writing a real number in scientific notation with six decimals in
a field 12 characters wide can be specified as %12.6e-4 . Complete documentation
of the printf -syntax is obtained by typing man sprintf or perldoc sprintf on
Unix/Linux systems (in general one can look up the online documentation of Perl's
sprintf function).
A dump function for writing u to an already opened file reads
function dump (fid, u, t0, dt)
% DUMP write array, containing the solution of an ODE, to file
n = length(u);
time = t0;
for i = 1:n
fprintf(fid, '%g %g\n', time, u(i));
time = time + dt;
end
One should note that strings in Matlab are always enclosed in single quotes.
In the main program there is no natural reading of input data from the command
line, since one usually operates Matlab interactively and sets variables directly in the
command interpreter. We therefore “hardcode” the input parameters tstop and dt :
15 This is not an issue for the programmer to worry about. On the other hand, when applying C
,
the programmer is actually required to gain the necessary knowledge and control the low-level
details of transferring arrays between functions.
CC
Search WWH ::




Custom Search