Information Technology Reference
In-Depth Information
Sect. 6.3.7 ). Recent extensions include the possibility to define classes and to trans-
late Matlab code to C CC . Well-trained users will often be able to generate highly
efficient Matlab code. For large or advanced scientific computing applications, Mat-
lab can seldom compete with tailor-made programs in the compiled languages
(Fortran, C/C CC ), but for simpler calculations and testing ideas, Matlab is a very
popular and productive tool.
The trapezoidal integration method is to be implemented in a Matlab function.
Any Matlab function we want to call from the interactive Matlab environment
or from a Matlab script must have its source code written in a file with exten-
sion .m . Such files are called M-files. In the present example, we create a file
Trapezoidal.m , containing more or less a direct translation of Algorithm 6.2 :
function r = Trapezoidal(a, b, f, n)
% TRAPEZOIDAL Numerical integration from a to b
% by the Trapezoidal rule
f = fcnchk(f);
h = (b-a)/n;
s=0;
x=a;
for i = 1:n-1
x=x+h;
s = s + feval(f,x);
end
s = 0.5 * (feval(f,a) + feval(f,b)) + s;
r=h * s;
The return parameter is called r and must be assigned before the end of this function.
Comment lines start with % . The first comment segment after the heading of the
function is taken as a documentation of the function and its usage if the first word is
the name of the function. Writing help Trapezoidal in Matlab will then print out
this documentation.
In Matlab, functions can be passed as arguments to other functions in various
ways. The statement f=fcnchk(f) makes a unified function representation f out of
different types of supplied function representations (names of M-files, strings with
function expressions, inline Matlab function objects).
The next three statements should be trivial to understand. The semicolon at the
end of each statement is not strictly required, but if you omit it, Matlab will echo the
statement to the screen. This is inconvenient (and takes much time) if the program
executes many statements (which is the case if you have loops).
For loops in Matlab are of the form for variable = expr ,where expr is a
loop expression. Typical loop expressions are
- a:b , which generates the sequence a , a+1 , a+2 , ::: , b ,and
- a:s:b , which generates the sequence a , a+s , a+2 * s , ::: , b .
In the present example we need an expression with step 1 from 1 to n . To call the
function f with argument x , we need to use the Matlab construction feval(f,x) .
A function to be integrated is naturally placed in another M-file, say, f1.m :
function y = f1(x)
y = exp(-x * x) * log(1+x * sin(x));
Search WWH ::




Custom Search