MATH3012 NUMERICAL ANALYSIS - LAB 2
2-D Graphic Input/Output
>> x=0:0.1:pi ; % gives a vector x starting from 0 till pi with increment 0.1
>> y=sin(2*x);
>> z=cos(2*x);
>> plot(x,y,-ro)
>> hold on
% to plot more than one graph in one frame
>> plot(x,z,--bx)
>> hold off
Graphic line specifications used in the plot() command
Line Type
- solid line
: dotted line
-- dashed line
-. Dash-dot
Point Type (Marker Symbol)
. (dot)
^ triangle
P makes a
star
d diamond
+ plus
v reversed
triangle
* asterisk
x xmark
s square
Color
r red
g green
b blue
k black
m magenta
y yellow
c cyan(sky
blue)
Mathematical Functions
Some functions provided by MATLAB
cos(x)
sin(x)
tan(x)
acos(x) % arccos(x)
asin(x) % arcsin(x)
atan(x) % arctan(x)
exp(x) % exponential function e^x
abs(x) % absolute value function
sqrt(x) % square root function
Creating your own function in MATLAB
1. We can define a simple function by using inline() command
>> f1=inline(1./(1+8*x.^2) ,x) % defines the function f1=1/(1+8*x^2)
f1 =
Inline function:
f1(x) = 1./(1+8*x.^2)
>> f1([0 1])
% evaluates function f1 for x=0 and x=1
ans =
1.0000
0.1111
>> feval(f1,[0 1]) % another way to evaluate function values by using feval
ans =
1.0000
0.1111
2. We can define a function by creating M-file name.m which has the following
general form:
function [outarg1, outarg2, ...] = name (inarg1, inarg2, ...)
outarg1 = ... ;
outarg2 = ... ;
You can type help function_name, MATLAB displays the comment lines that
appear between the function definition line and the first non-comment
(executable or blanck) line.
Example Create a new m-file and type the following lines in it.
function y = f49(x) % creates a vector valued function in R^2.
y(1) = x(1)*x(1) + x(2)*x(2) -1;
% the first component of that vector
y(2) = 2*x(1)*x(1) -3* x(2)*x(2) -2; % the second component of that vector
Now save m-file and return to the command window.
>> f49([0 1])
% calculates the 2-D vector function f49 at x=0 and x=1
ans =
0
-5
>> feval(f49,[0 1]) % another way to evaluate function values
ans =
0
-5
Working with Polynomials
>> p= [1 0 -3 2]; % vector p is used to represent polynomial p(x)=x^3-3x+2
>> p(1) % gives the first element of p; note that p is stored as a vector
ans =
1
>> polyval(p,1) % calculates the value of the polynomial p(x) at x=1
ans =
0
>> polyval(p,[0 1 2]) % calculates the value of p(x) at x=0, x=1, and x=2
ans =
2
The multiplication of two polynomials can be done by using command conv
>> a = [1 -1]; % a(x)=x-1
>> b = [1 1 1]; % b(x)=x^2+x+1
>> c=conv(a,b) % gives the polynomial c(x)=(x-1)*( x^2+x+1)=x^3-1
c=
1
-1
Polynomial division can be done by using command deconv
>> d=deconv(c,a) % gives the polynomial d(x)=(x^3-1)/(x-1)=x^2+x+1
d=
1