Matlablectures
Matlablectures
Contents
2 Scripts 3
3 Setting up vectors 4
5 Plotting 8
6 Printing data 9
7 For loops 10
8 While loops 10
9 Functions 11
1
1 Example: Plotting a function
Starting MATLAB:
Windows: search for MATLAB icon or link and click
Linux: % ssh linux.unm.edu
% matlab
or
% matlab -nojvm
Sample MATLAB code illustrating several Matlab features; code to plot the graph of y =
sin(2πx), x ∈ [0, 1]: What is really going on when you use software to graph a function?
2. The points (xk , yk ) are then plotted together with some interpolant of the data (piece-
wise linear or a smoother curve such as splines of Bezier curves).
In MATLAB you specify xk , then compute yk . The command plot(x,y) outputs a piecewise
linear interpolant of the data.
Notes:
(1) The % sign denotes the begining of a comment. Code is well commented!
(3) The semicolon prevents displaying intermediate results (try it, what happens if you omit
it?)
2
(4) length,zeros,sin,plot are built in MATLAB functions. Later on we will write our
own functions.
(5) In Matlab variables are defined when they are used. Reason for y=zeros(1,n): allocate
amount of memory for variable y; initialize. How much memory space is allocated to y if
that line is absent, as you step through the loop? Why is zeros not used before defining x?
(6) In Matlab all variables are matrices. Column vectors are nx1, row vectors are 1xn, scalars
are 1x1 matrices. What is output of size(x)?
(7) All vectors/matrices are indexed starting with 1. What is x(1), x(2), x(10), x(0)?
(8) Square brackets are used to define vectors. Round brackets are used to access entries in
vectors.
plot(x,y,’*’)
plot(x,y,’*-’)
plot(x,y,’*-r’)
See Tutorial for further plotting options. Lets create a second vector z = cos(2πx) and plot
both y vs x in red dashed curve with circle markers, and z in green solid curve with crosses
as markers. Then use default. But first:
2 Scripts
MATLAB Script m-file: A file (appended with .m) stored in a directory containing MATLAB
code. From now on I will write all code in scripts so I can easily modify it. To write above
code in script:
3
Save your work on Floppy or USBport, or ftp to other machine. No guarantees that your
folders will be saved.
Now I’d like to modify this code and use more points to obtain a better plot by changing
the line defining x, using spacing of 1/100 instead of 1/10. But how to set up x with 101
entries??
3 Setting up vectors
Row Vectors
• Explicit list
x=[0 1 2 3 4 5];
x=[0,1,2,3,4,5];
• Using a:increment:b. To set up a vector from x=a to x=b in increments of size h you
can use
x=a:h:b;
Here you specify beginning and endpoints, and stepsize. Most natural to me. However,
if (b-a) is not an integer multiple of stepsize, endpoint will be omitted. Note, if h
omitted, default stepsize =1. What is?
x=0:0.1:1;
x=0:5;
• Using linspace
x=linspace(a,b,n);
Column Vectors
• Explicit list
x=[0;1;2;3;4;5];
4
• Transpose row vector
x=[0:.1:1]’;
Matrices
How to access entry in second row, first column? WHat is A(1,1), A(2,0)?
y=sin(2*pi*x);
The sine function is applied to a vector x and applies the sine operation to each entry in the
vector. This is the same as
y(1:n)=sin(2*pi*x(1:n));
k=1:n
y(k)=sin(2*pi*x(k));
Note that this looks almost like the for loop in the example in §1.1 but it is not a loop. All
entries of y are set at once. We can now give a short version of the MATLAB code to plot
the graph of y = sin(2πx):
x=0:.01:1;
y=sin(2*pi*x);
plot(x,y)
5
Since vectors are special cases of matrices, the above operation can also be applied to ma-
trices. The statement B=sin(A) applies the sine function to every entry in A.
A=[1 1 1
2 0 -1
3 -1 2
0 1 -1
];
(the commas and semicolons are not necessary in this form). If you create, possibly using
FORTRAN or C, a file that contains a matrix of numbers, and enter A=[ and ]; before and
after, you can read these numbers in as a script. For example, I created (in FORTRAN) a
file called t22dat.m that contains the following lines
...
(where the dots denote the remaining 2390 lines). I can now read this matrix into MATLAB
and extract the vectors t and ylmb for example as follows
6
Note: entries of vectors are accessed using round brackets. Vectors are defined using square
brackets.
If x is a vector, what is
x*x
? Answer: error!, Inner matrix dimensions dont agree. If x is a row vector, and y is a column
vector, what is
x*y
PN
Answer:
qP the inner product k=1 xk yk . For example to compute the Euclidean norm of x,
N 2
k=1 xk you can use the one-line code
euclidnormx=sqrt(x*x’);
What is
y*x
What if you instead of plotting y = sin(x) you want to plot y = x2 ? Given a vector x you
want to create a vector y whose entries are the square of the entries of x. The following
x=0:.01:1;
y=x*x;
or
y=x^2; %the hat is MATLABs symbol for exponentiation
7
wont work. Instead, to perform componentwise operations you need to add a . in the correct
place. Try
y=x.^2;
y=A.^2;
y=1./x;
y=x.*z; %where x,z are vectors/matrices of same length
s=sum(x);
5 Plotting
8
plot(x,y1)
hold on
plot(x,y2)
hold off
Type help hold to see what this does. If you dont want to save the previous plot you can
view consecutive plots using pause command in your script (what happens if pause is missing
from below?)
plot(x,y1)
pause
plot(x,y2)
6 Printing data
Printing tables:
disp(’ x sin(x)’)
for k=1:n
disp(sprintf(’%3.1f %6.4f’, x(k),y(k)));
end
What does the format %3.1f specify? Type help sprintf to see how to format integers,
character strings, etc.
Printing figure:
9
7 For loops
FOR variable=expr
statements
END
n = 10;
for i=1:n
for j=1:n
a(i,j) = 1/(i+j-1);
end
end
8 While loops
WHILE expression
statement
END
10
9 Functions
MATLAB Functions are similar to functions in Fortran or C. They enable us to write the
code more efficiently, and in a more readable manner.
The code for a MATLAB function must be placed in a separate .m file having the same name
as the function. The general structure for the function is
<function body>
• Somewhere in the function body the desired value must be assigned to the output
variable!
• Comments that completely specify the function should be given immediately after the
function statement. The specification should describe the output and detail all input
value assumptions.
• The lead block of comments after the function statement is displayed when the func-
tion is probed using help.
• All variables inside the function are local and are not part of the MATLAB workspace
Exercise 1: Write a function with input parameters x and n that evaluates the nth order Taylor
approximation of ex . Write a script that calls the function for various values of n and
plots the error in the approximation.
function y=ApproxExp(x,n);
% Output parameter: y (nth order Taylor approximation of $e^x$)
% Input parameters: x (scalar)
% n (integer)
sumo = 1;
for k=1:n
sumo = sumo + x^k/factorial(k);
end
y = sumo;
11
(What does this code do? First, set k=1. Then k=2. Then k=3. etc. Write out the
result after each time through loop.) A script that references the above function and plots
approximation error is:
x=4;
for n=1:10
z(n) =ApproxExp(x,n)
end
exact=exp(4)
plot(abs(exact-z))
Example: An example of a function that outputs more than one variable. The function computes
the approximate derivative of function fname, the error in the approximation, and
the estimated error. The following code is written in a file called MyDeriv.m:
function [d,err]=MyDeriv(fname,dfname,a,h);
% Output parameter: d (approximate derivative using
% finite difference (f(h+h)-f(a))/h)
% err (approximation error)
% Input parameters: fname (name of function)
% dfname (name of derivative function)
% a (point at which derivative approx)
% h (stepsize)
d = ( fname(a+h)-fname(a) )/h;
err = abs(d-dfname(a));
(Note: this works using MATLAB versions 7.0 but not 6.1. For an older MATLAB version
you may have to use the feval command. See help, Daishu or me.)
A script that references the above function and plots the approximation error:
a=1;
h=logspace(-1,-16,16);
n=length(h);
for i=1:n
[d(i),err(i)]=MyDeriv(@sin,@cos,a,h(i));
end
loglog(h,err)
12
Exercise: What happens if you call
d=MyDeriv(@sin,@cos,a,h)
or simply
MyDeriv(@sin,@cos,a,h)
You can replace sin and cos by user defined functions, for example ’f1’ and ’df1’. Do
it. That is, you need to write the function that evaluates f1 and df1 at x (in files f1.m and
df1.m).
13