Matlab Course
Matlab Course
Course one
Lecture 1
What Is MATLAB?
MATLAB is a high-performance language for technical computing. It
integrates computation, visualization, and programming in an easy-to-use
environment where problems and solutions are expressed in familiar
mathematical notation.
Typical uses include
Math and computation
Algorithm development
Data acquisition
Modeling, simulation, and prototyping
Data analysis, exploration, and visualization
Scientific and engineering graphics
Application development, including graphical user interface building.
The first line denotes the range over which this loop is executed
The second line is the body in which the actual computation takes place
The third line denotes the end of the loop. Note: try semicolon (;) after i^2;
More often loop variables are used to index into arrays and matrices,
rather than involving the loop variable directly in a computation.
a=[3,40,1,8,0], b=[-7,5,-.4,16,1], c=[ ];
for i=1:5 c(i) = a(i) + b(i); end
Note: try c(1), c(2), etc.
the loop above can be generalized so that the loop statements are not
confined to only 5 element vector.
for i=1:length(a)
c(i) = a(i) + b(i);
end
To iterate over an entire matrix, we thus need to iterate over every row
and for each row over every column. This is called a nested loop, i.e. a
loop within a loop:
m=[1,2,3,4;5,6,7,8;9,10,11,12];
for i=1:3
for j=1:4
m(i,j) = m(i,j) * 2;
end;
end
the loop above can be generalized so that the loop statements are
not confined to only 3*4 matrices.
m=[1,2,3,4;5,6,7,8;9,10,11,12]
l=size(m)
for i=1:l(1)
for j=1:l(2)
m(i,j) = m(i,j) * 2;
end
end
while loops
The "while" loop is used in scenarios in which the range is not well defined,
for example in user input.
a=[3,40,1,8,0]; b=[-7,5,-.4,16,1];c=[ ];
i=1;
while (i <= 5)
c(i) = a(i) + b(i);
i=i+1;
end;
Even though the image appears to have two dimensions, it really only has
one. The one row of the image is stretched in the vertical dimension.
The lowest intensity as defined in the loop is 1, because the loop iterates
from 1 to 255, when in fact the lowest real intensity is 0. However, given the
above loop, we cannot define a range from 0 to 255, because i is used to
index into the matrix. As there are no 0 indices in Matlab, this would cause
an error. One possible correct loop would be:
for i=1:255
grad(1,i,1)=i;
grad(1,i,2)=0;
grad(1,i,3)=0;
end
image(uint8(grad));
we will build a one dimensional image in which red fades into green, in this
case the loop would need to decrement the red value and increment the
green value at the same time:
for i=1:256
grad(1,i,1)=255 - (i-1);
grad(1,i,2)=i-1;
grad(1,i,3)=0;
end
image(uint8(grad));
3.2.2 Images - Nested Loops
For an example of a nested loop, we will alter the Red, Green, and Blue
color channels in the cartmancop.jpg image. In the first example,
consider removing all of the green color:
cartman=imread('cartmancop.jpg');
s=size(cartman);
for i=1:s(1)
for j=1:s(2)
cartman(i,j,2) = 0;
end
end
image(cartman);
In this example we will reproduce the effect of a badly developed
photograph which is overexposed on one side and darker on the other. This
essentially means that for each row of pixels we will increase the
brightness/contrast in the left portion and decrease brightness/contrast in
the right portion.
cartman=double(imread('cartmancop.jpg'));
s=size(cartman);
for i=1:s(1)
for j=1:s(2)
cartman(i,j,1) = cartman(i,j,1) * 70/j + i;
cartman(i,j,2) = cartman(i,j,2) * 70/j + i;
cartman(i,j,3) = cartman(i,j,3) * 70/j + i;
end
end
image(uint8(cartman));
if else statement
if expression
(commands evaluated if True)
else
(commands evaluated if False)
end
if x == 10
msgbox ('ok', 'result');
else
msgbox ('no', 'result');
end;
if elseif else statement
if expression1
(commands evaluated if expression1 is true)
elseif expression2
(commands evaluated if expression2 is true)
elseif expression3
(commands evaluated if expression3 is true)
elseif expression4
(commands evaluated if expression4 is true)
.
.
else
(commands evaluated if no other expression is true)
end
>> x = 11;
>> if x == 1
disp ('1');
elseif x == 2
disp ('2');
else
disp ('3');
end;
Symbol Example Symbo
Example
l
greater than or equal to >= (a >= b) Both expressions must be valid (True) in &&
(a > b) order for the overall expression to be
greater than > (a && b)
valid (True)
equals == (a == b)
< (a < b) (a || b)
less than
Either one of the expressions must be
less than or equal to <= (a <= b) valid (True) in order for the overall ||
expression to be valid (True)
not equal to ~= (7 ~= 6)
A=[1 2 ;3 4]
B=[ 1 2;3 4]
if A==B C=A+B; end;
if A(1,1) == B(1,1) && A(1,2) == B(1,2) C=A+B; end;
if A(1,1) == B(1,1) || A(1,2) == B(1,2) C=A+B; end;
4.2 Conditionals - Examples
4.2.1 Color Clipping
In this example, we will change the color palette of an image by clipping all
dark pixels below some threshold, that is these dark pixels will be set to
intensity 0 (or 255). The resulting image then only contains color values
that are above the threshold intensity.
For the first example, the threshold is set to 120. Any color value below
120 will be set to 0. We will make use of a triple loop, where the outermost
loop iterates over rows, the middle loop iterates over columns, and the
innermost loop iterates over the three color values Red, Green, and Blue.
cartman=imread('cartmancop.jpg');
l=size(cartman);
for i=1:l(1)
for j=1:l(2)
for k=1:3
if (cartman(i,j,k) < 120)
cartman(i,j,k) = 0;
end
end
end
end
image(cartman);
cartman=imread('cartmancop.jpg');
l=size(cartman);
for i=1:l(1)
for j=1:l(2)
for k=1:3
if (cartman(i,j,k) < 120)
cartman(i,j,k) = 255;
end
end
end
end
image(cartman);
Finally, we can attenuate and amplify the color intensities depending on
a threshold. Consider setting the intensity of a pixel to 0 if it is below the
threshold and 255 if it is above the threshold:
cartman=imread('cartmancop.jpg');
l=size(cartman);
for i=1:l(1)
for j=1:l(2)
for k=1:3
if (cartman(i,j,k) > 100)
cartman(i,j,k) = 255;
else
cartman(i,j,k) = 0;
end
end
end
end
end
image(cartman);
With this effect the image is reduced to a very small number of colors,
namely the most extreme ones: Black (0,0,0), Red (255,0,0), Green
(0,255,0), Blue (0,0,255), Yellow (255,255,0), Magenta (255,0,255),
Cyan (0,255,255), and White (255,255,255).
4.3 m-files and Functions
We have thus far used m-files for aggregating expressions and
evaluating them all by executing the m-file. However, m-files serve
another more important purpose: they are used to define functions in
Matlab. We have already been using several functions, such as imread,
wavplay, rand, etc., all of which are by default present in Matlab and
have been added to the Matlab package by MathWorks, the company
that develops Matlab.
A function is formally defined as something that takes one or more
arguments, computes something based on those arguments, and
returns a value. In the case of imread, the argument is an image file
name and the return value is the raw image data stored in a matrix.
Figure below outlines all of the parts of a simple function. A function is
defined in an m-file with the function keyword on the first line. The
remainder of the first line is the function declaration which is similar to a
mathematical function, e.g. z = f(x, y). z is the return variable, i.e. the
variable that holds the final value of the function. x and y are arguments
passed to the function from the Matlab Command Window. f is the name
of the function, which must be reflected in the m-file's name. This
function f, for example, must be stored in an m-file by the name of f.m .
Immediately following the first line of a function is a series of
comments. A comment is a line of text that is not executed, but
instead serves as a note. Comment lines must begin with the percent
symbol %. When typing into the Command Window 'help rand', it is
these commented lines after the function declaration that are printed.
The actual computation of values takes place in the body of the
function. The return value of the function (z in this case) must appear
somewhere near the end of the body where it is assigned to the final
value of the function. It is this value that is returned to the Command
Window as the function's result.
Figure below shows the flow of a function's execution. This flow
corresponds to the previous discussion of a function's logical setup.
For an example of a function that will be used in later exercises and
assignments, we will create a function that converts velocity from
kilometers per hour to meters per second: function v_kmh2msec
Make sure that that the Current Directory points to a directory in your
account, which you can use to store all Matlab related functions,
exercises, and assignments.
To create a new m-file, select File -> New -> m-file. This will bring up
an empty Text File Editor.
We begin our function with the function declaration:
function v = v_kmh2msec(kmh)
We continue by including a few comments that describe the purpose
and usage of this function:
% V_KMH2MSEC kilometers per hour
% V_KMH2MSEC(KMH) converts
% kilometers per hour KMH to
% meters per second
It is good programming practice to do some form of error checking. A
useful function to include is nargchk, which checks the number of
arguments passed to the function.
Function nargchk takes 3 arguments:
1. smallest number of valid arguments
2. largest number of arguments
3. the actual number of passed arguments, denoted by the built-in
variable nargin (number of arguments passed into the function)
Function nargchk is further passed to function error which displays an
actual error message.
If our function required 3 arguments, the function call would look as
follows: error(nargchk(3, 3, nargin))
If our function required either 2 or 3 arguments, the function call would
look as follows: error(nargchk(2, 3, nargin))
In the case of kmh2msec, we require at least 1 and at most one
argument, making the function call: error(nargchk(1, 1, nargin))
Finally, the main body of the function contains the conversion from
km/h to m/sec:
v = kmh * 1000 / 60 / 60
Save the m-file from the File -> Save menu, and name it after the
function name, v_kmh2msec
In the Command Windows, we can finally try out the function:
v_kmh2msec(1) returns a valid number, 0.2778
v_kmh2msec( ) returns an error message, as there are not enough
number of arguments
v_kmh2msec(1, 2) returns an error message, as the number of
arguments exceed the requirement
help v_kmh2msec returns the lines of comments immediately after the
function declaration. The help command can be used on every built-in
function, and every other function that features help comments.
v_kmh2msec(-10) returns a valid mathematical number, but is
physically impossible. We should build the function so that negative
numbers are not converted.
To edit the m-file, click on the tab Current Directory in the Workspace
window, then right-click on the function v_kmh2msec and select Open
as Text, or simply double-click on the entry.
We will modify the code to include a standard if-then-else statement. In
the if clause, we will check whether the passed argument of kmh is
negative.
if (kmh < 0)
v = 0;
else
v = kmh * 1000 / 60 / 60;
end
function v = v_kmh2msec(kmh)
% V_KMH2MSEC kilometers per hour
% V_KMH2MSEC(KMH) converts
% kilometers per hour KMH to
% meters per second
error(nargchk(1, 1, nargin))
if (kmh < 0)
v = 0;
else
v = kmh * 1000 / 60 / 60;
end
Lecture 5
5.1 Plotting
In Matlab, plotting refers to producing 2-dimensional graphs, while
meshing refers to 3-dimensional graphs. Since a 2-dimensional graph is
merely a collection of points, the command plot takes as input a vector
and simply plots the numbers.
Given vector Y, the command plot(Y) plots the point in the vector. Without
passing a separate vector with x-values, each point in vector Y is
mapped linearly to a point on the x-axis. For example, if Y = [10, 7, -9, 0,
1] , then the corresponding X values are [1, 2, 3, 4, 5] , respectively. If
this scale is not desirable, an X vector with a different scale can be
passed as an argument to the function plot.
Y = [10, 7, -9, 0, 1]
plot(Y)
X=[-4 0 5 40 140]
plot(X,Y)
For example, consider the following data points:
y=[16,50,70,104,106,104,95,80,67,59,87,124,153,157,144,127,...
109,90,71,100,134,163,178,179,174,161,141,117,93,76,89,105,...
123,140,153,156,144,128,106,86,65,48,30,17,24,29,25,21,16,7];
plot(y);
x=[10,5,3,2,9,14,17,20,25,27,28,29,30,38,45,49,52,54,58,...
59,60,62,66,72,78,81,82,84,87,90,97,102,106,109,112,119,...
125,128,126,122,118,117,121,134,154,174,190,194,194,185];
plot(x,y);
At most one modifier can be taken from each column and concatenated
to result in a unique line/point/color style. For example:
plot(x,y,'r');
whitebg('k')
xBar=[1:10];
yBar=rand(1,10) * 100;
yBar=rand(7,3);
bar(yBar);
3D bar graphs are easily obtained from matrices as well, using the bar3
command:
bar3(yBar);
5.1.2 Labels
Common properties of all figures, whether 2D or 3D, plots, bar graphs,
meshed, etc. are axes labels, titles. Every figure should be properly
labeled for clarity.
Axes labels can be assigned using commands xlabel , ylabel , or zlabel ,
selectively or in combination:
y=rand(10, 3);
plot(y);
5.1. 4 Meshing (3d graphs)
3D graphs are generated using the function mesh or surf . Given a 2D
matrix of values, each value is used as a z-value (elevation), and
placed in a 3D view.
Given a function of sine and cosine:
z=[ ];
for i=1:100
for j=1:100
z(i,j) = sin(i/10) + cos(j/10);
end
end
mesh(z);
[X,Y] = meshgrid(-3:.125:3);
Z = peaks(X,Y);
meshc(X,Y,Z);
axis([-3 3 -3 3 -10 5])
[X,Y] = meshgrid(-3:.125:3);
Z = peaks(X,Y);
meshz(X,Y,Z)
surf(z);