This is a simple tutorial to get you started with Matlab. Matlab makes it easy to perform scientific computations without having to learn a programming language such as Fortran, C, or C++. This tutorial is developed keeping assignment_0.pdf for AM205 in mind. It can be used for other classes or self-learning as well.
- Matlab Basics: start up, simple commands, Matlab as calculator
- Matlab Variables: Vectors and Matrices
- Linear Equations
- Simple programming: control of flow, functions, m-files
You should make use of online search tools such as google to search for relevant matlab material. There is a lot of material on the web. Additional resources include:
This depends on your operating system. On Mac, it is usually installed in /Applications and you should see a Matlab icon with a MATLAB_<version number>. Double clicking the icon should open it. On Windows, there should either be a shortcut on the desktop or it can be found under programs in the start-up.
Matlab Development Environment (Matlab Desktop):
This can change with new releases. The following video gives a quick introduction:
The key items are "Command Window" (where you type commands in this tutorial), "Current Folder", and the "Workspace".
Note: In Matlab, any line beginning with % is a comment (not executed by matlab). Lines without % are commands that are executed by matlab. You can copy and paste the matlab statements in this tutorial into matlab
Open matlab and in the command window, type:
This will open a separate window with documentation and a search box. There are other ways! For example, if you want to find out more about a specific command, you can do:
%As an example, to find out more about print:
% when in doubt, try help!
For space reasons, the results are not shown in the code block unless necessary.
%Matlab can be used as a calculator (with +, -, *, / indicating addition, subtraction, multiplication and division)
%Exponentiation is done with ^
% Square root operation with 'sqrt'
%Matlab already knows the meaning of some variables, eg, pi
log(pi) %natural logarithm of pi
log10(pi) %logarithm with base 10
%you can use the format command to change the output format for numbers
%for details on format, type
%example of long format:
pi % displays 3.141592653589793
pi % displays 3.1416
All matlab variables are arrays. Even single numbers are arrays of dimension 1. Below, we start experimenting with some arrays.
% The array x contains numbers ranging from 0 to 1.0 in increments of 0.25.
% Note that the ";" at the end suppresses the output. Experiment by leaving it out.
% typing x (without semi-colon) will output the array
%The same array can be created with a simpler command.
%The following syntax with ":" indicates that the array starts from 0
% and is incremented by 0.25 till we reach 1.0. This is much easier for larger
% arrays (such as the array t, which contains 100 numbers).
%The following (without brackets) also creates an array.
% The function 'linspace' can be used to create an array of 100 equally spaced elements.
v=linspace(0,1.0); note that the default is 100 equally spaced points between 0 and 1.
% To create an equally spaced array between 1 and 1.0 with 5 points
x=linspace(0,1.0,5); the third argument specifies the number of points.
% Sum of elements of an array
% Note we already have created an array t before! We create a second array:
x=2*pi*t; This multiplies each element of t by the scalar 2*pi.
% y will be an array consisting of sin of the elements of the array x
Element-wise operations on an array
%Sometimes we need to carry out operations on individual elements of an array.
%Let us start with an array x
%We would like to square each element of the array. In mathlab, this can be done with:
x.^2 % Notice the dot (.) in front of exponentiation (^).
% 0 0.0625 0.2500 0.5625 1.0000
%Element-wise operations work on Matrices too!
% We have already created arrays x and y. We can now plot y as a function of x.
xlabel('angle'); % will add x-label
ylabel('Amplitude'); % will add y-label
title('Plot of sin(\Theta)') % adds a title. Note \Theta is from the Latex typesetting program.
More on plotting later.
v1=[1.5,-2,4,10]; % A 1-dimensional array can be handled as a vector.
Example – Dot product, angle between vectors:
v2=[3.1,-1,2,2.5]; %Another 1-dimensional array
%The two arrays v1 and v2 are basically vectors with all the vector operations defined.
dot(v1,v2); %dot product of two vectors
% Angle between the vectors v1 and v2
% To compute the angle between two vectors, we need the magnitude of the two vectors
abs_v1=sqrt(sum(v1.^2)) % Notice we are performing element-wise exponentiation (i.e. .^2)
costheta=dot(v1,v2)/(abs_v1*abs_v2); cosine of the angle between the vectors
% An easier way: instead of computing the magnitude yourself, you can use the norm function
%To find out more about norm, do:
help norm % warning: the response is detailed and technical!
theta=acos(costheta); %Now compute the angle (in radians) between the vectors.
% convert radians to degrees
% convert degrees to radians
%A matrix consisting of two rows and 6 columns is defined
%like an array except that the two rows are separated by ";"
%Notice how the semicolon symbol (;) can take on different meanings depending
%on the context. Below you see it used to define a matrix and to suppress the output.
1.0000 1.2000 1.4000 1.6000 1.8000 2.0000
2.0000 2.2000 2.4000 2.6000 2.8000 3.0000
% output: 1.0000 1.2000 1.4000 1.6000 1.8000 2.0000
% 2.0000 2.2000 2.4000 2.6000 2.8000 3.0000
% Transpose of a matrix is obtained by superscripting a matrix with the prime character, i.e. "'":
y=x' % transpose of x
% We extract the last four columns of the second row by "slicing":
% 2.4000 2.6000 2.8000 3.0000
% Random matrix, identity matrix, etc.:
% 0.8147 0.1270
% 0.9058 0.9134
% Note: you won't get the same matrix! why? hint is in the name.
%A 3X3 Identity matrix:
% 1 0 0
% 0 1 0
% 0 0 1
%Determinant of a matrix obtained with det function (defined only for square matrices)
% the answer should be 420.0
% Inverse of a matrix obtained with inv function.
% 0.1071 0.1786 -0.0357
% 0.0857 -0.0571 -0.0286
% 0.1595 0.0881 -0.1643
%product of a matrix with its determinant should ideally be an identity matrix.
% In practice, it will be close but may not be exact.
% 1.0000 0 0.0000
% 0.0000 1.0000 -0.0000
% -0.0000 -0.0000 1.0000
Matrix example (Linear Equations)
We now solve the linear equation:
A=[2 4 3;1 -2 -2;-3 3 2];
% Use of the backslash operator (\) is a more efficient way:
% Let us conside the Taylor series for the sin function
% The series is summation over
% n (from 1 to k) of (-1)^(n-1)x^(2n-1)/(2n-1)\!
% For an arbitrary number of terms k, how do we evaluate sin(x) for a given
% value of x?
% The task is one of carrying out summation of k terms. This is
% accomplished via the "for" loop. The syntax is:
% for i=1:k
% (do some operations that depend on i)
% For the sin series, here is one way to implement the summation:
sinfunc=0; % initialize the sin function
sinfunc=sinfunc+kcoef*x.^km1/factorial(km1); %This is the summation step. On the right hand side, The k'th term
% of the series is evaluated and added to the previously stored value
% of sin function. Then sincfunc (left hand side) is replaced with the
% new value on teh right hand side.
sinfunc % sinfunc contains the approximation of sin(x)
err=sin(x)-val; % you can easily calculate the error
We will later consider the control of flow within a loop under functions.
More advanced topics
complex plots (plot annotations, axis labels, etc.)
x = -pi:.1:pi;
y = sin(x);
p = plot(x,y)
% gca returns the handle to the current axes for the current figure.
% \pi, \leq, \Theta are all from "latex" typesetting system.
xlabel('-\pi \leq \Theta \leq \pi')
title('Plot of sin(\Theta)')
% \Theta appears as a Greek symbol (see String)
% Annotate the point (-pi/4, sin(-pi/4))
text(-pi/4,sin(-pi/4),'\leftarrow sin(-\pi\div4)',... % Notice the line continuation with ellipsis (...)
% Change the line color to red and
% set the line width to 2 points
Some 3D plotting
%If we have two arrays that define two orthogonal axes, matlab makes it easy to
%produce a grid from the axes to form the basis for plotting.
%This is done with the meshgrid command. Let's define the two axes and see how the meshgrid command works.
x=[-8:4:8]; % an array of points on the x-axis [-8 -4 0 4 8]
y=[-8:4:8]; % an array of points on the y-axis [-8 -4 0 4 8]
[X Y]=meshgrid(x,y) % returns two matrices X and Y:
% -8 -4 0 4 8
% -8 -4 0 4 8
% -8 -4 0 4 8
% -8 -4 0 4 8
% -8 -4 0 4 8
% -8 -8 -8 -8 -8
% -4 -4 -4 -4 -4
% 0 0 0 0 0
% 4 4 4 4 4
% 8 8 8 8 8
% Note (X[j],Y[j]) define points in the 2D space defined by the x and y axes.
% Thus, if we have a function defined on x and y, i.e. f(x,y),
% evaluation of the function over all the ordered pairs of points
% in x and y can now use the whole matrices X and Y instead of looping
% over all the points. See below for an example of how this is done in the
% context of a 3D plot below.
Sinc function (https://en.wikipedia.org/wiki/Sinc_function)
% Plot of 3D sinc function.
% Look up "meshgrid" in matlab document
% Returns rectangular grid
R = sqrt(X.^2 + Y.^2); % Notice how element-wise operation is used.
Z = sin(R)./R; % Sinc function
surf(Z); % surface plot
mesh(Z); % mesh plot
contour(Z); % contour plot
[X,Y] = meshgrid(-2:.2:2, -2:.2:2);
Z = X .* exp(-X.^2 - Y.^2);
m-FILES (SCRIPTS AND FUNCTIONS)
A collection of matlab commands in a file named <name>.m.
To run the script, save the script file (say example.m) in a directory accessible by matlab and just type the script name (without .m) in the command window. In this case it will be 'example'.
Matlab functions are callable sub-procedures that are
put in a file named <function_name>.m
Example function (stat.m from matlab documentation) is as follows:
function [mean,stdev] = stat(x)
% x, which is an array of numbers, is the input
% mean and stdev are the return values (outputs)
n = length(x);
mean = sum(x)/n;
stdev = sqrt(sum((x-mean).^2/n));
Put the above function in a file called stat.m in a directory which is in matlab's path. You can use this function as below:
The following are some functions relevant to assignment_0.pdf of AM205.
They are meant to get you started with the problems, but they are not "complete solutions".They can be useful for learning functions in matlab for other classes as well.
function [m,val] = cheby(k,x)
% Chebyshev polynomial recurrent relation
% Relevant to question 2 in assignment_0
% Note: x and k are not vectors.
if k==0 % if ... elseif.. block controls the flow
% based on the value of k in this example.
function [sinfunc,err] = sinTaylorSeries(k,x)
% The Taylor series for the sin function
% The series is summation over
% n (from 1 to k) of (-1)^(n-1)x^(2n-1)/(2n-1)\!
% Relevant to question 5 of assignment_0.
% Note x is a vector.
function [deriv,act,err] = tanderiv(x,h)
% Derivative of tan: (tan(x+h)-tan(x-h))/2h
% relevant to question 4 in assignment_0.
% Note x and h are not vectors.
Image Processing (Quick Introduction)
Here are the images we will be using: baboon.png and Brain-MRI.jpg
%%The primary functions for loading images is 'imread' and for displaying images is 'imshow'.
%% Images are basically two dimensional array of pixels (picture elements) with a third dimension
%% that shows the intensity of pixel. If the image is a gray scale image,, the intensity is a single number
%% at each pixel. If it is a color image, it is stored as a "third dimension" with 3 value
%% each corresponding to the intensity of r (red), g (green) and b (blue) colors. Thus if we do:
%% The result is 512 512 3, which indicates it is a two dimensional array of 512 x 512 pixels with three colors.
%% To get the 'red' intensity, you can do:
r=im(:, :, 1);
%% This is now a two dimensional array. The color intensity can vary anywhere from 8 bits (256 levels)
%% for grayscale to 24 bits (8 bits for each color) for color images. There are even 30-, 36-, or 48- bit
%% images. As far as Matlab is concerned,. the image once loaded is a three dimensional array with the last
%% dimension taking on only 3 values.
%% will show 255 and 0 (the red color is stored in 8 bits).
%% will show the image in grayscale with intensity corresponding to "red" color intensity in the
%% original image. You can convert the color image to a grayscale image:
This is now a two dimensional image with a grayscale intensity of 8 bits. We have compressed the image
at the expense of color!
%% Many medical images (such as MRI, CT, ultrasound, etc.) are likely to be grayscale images.
%% They can 10 or 12 bit images and it is convenient to represent them using 16 bits as computers can 16 bits efficiently.
%% We can convert this to an grayscale image with:
%% This will be a 2D array of pixels with gray shades represented by 8 bits (256 shades).
%% We can plot a histogram of color intensity (x-axis intensity, y axis -- number of pixels) with:
%% We can reduce the variation in the intensity among the pixels (and thereby visually enhance the darker regions)
%% by using the matlab function histeq.
%%will display the image with formerly darker regions more bright and brighter regions darker.