Professional Documents
Culture Documents
Class8 Lab
Class8 Lab
ECE 002
Professor S. Ahmadi
Tutorial Outline
• Functions using M-files.
• Numerical Integration using the
Trapezoidal Rule.
• Example #1: Numerical Integration using
Standard Programming (Slow).
• Example #2: Numerical Integration using
Vectorized MATLAB operations (Fast).
• Student Lab Exercises.
What Are Function M-Files
• Function M-files are user-defined subroutines
that can be invoked in order to perform specific
functions.
• Input arguments are used to feed information to
the function.
• Output arguments store the results.
• EX: a = sin(d).
• All variables within the function are local, except
outputs.
NOTE: Local variables are variables that are only used within the
function. They are not saved after the M-file executes.
Example of a Function M-File
function answer = average3(arg1,arg2, arg3)
answer = (arg1+arg2+arg3)/3;
How to call a function in matlab
X = sin(pi);
% call the interior function of Matlab, sin
Y=average3(1, 2, 3);.
% average3 is a user-defined function.
% The average value of 1,2 and 3 will be stored in Y
Example: Calling a Function from
within the Main program.
% Example1: This is a main program example to
illustrate how functions are called.
% input is a function that requests information from
% the user during runtime.
∫ f(x) dx ≈ ∑ ci f(xi)
a i=0
Simplify:
½ ((b-a)/2) [ f(a) + f(x1) + f(x1) + f(b) ]
b x1 x2 b
in=1:n-1;
xpoints=a+in*h; % Defining the x-points
ypoints=feval(vectorize(f),xpoints); % Get corresponding y-points
sig=2*sum(ypoints); % Summing up values in ypoints, and mult. by 2
s=s+sig+feval(f,b); % Evaluating last term
I=s*h/2;
Example 3: Integrating Trapezoidal/FastTrap
Function into Main Program
• Main program to test numerical integration function,
and to measure difference in speed between the two
previous functions.
% Example 3: Main program to run the numerical integration function,
% using the user-created Trapezoidal/FastTrap methods.