Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
100 views

Matlab Course

MATLAB is a programming language for technical computing. It allows matrix manipulations, plotting of data, implementation of algorithms, modeling and simulation. [It features tools for computation, programming, visualization, and add-on toolboxes for specific domains like signal processing.] MATLAB uses matrices and vectors for all variables and operations, with matrices indexed starting at 1. It provides functions for common math operations on matrices and vectors as well as random number generation and plotting of data.

Uploaded by

Mona Ali
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
100 views

Matlab Course

MATLAB is a programming language for technical computing. It allows matrix manipulations, plotting of data, implementation of algorithms, modeling and simulation. [It features tools for computation, programming, visualization, and add-on toolboxes for specific domains like signal processing.] MATLAB uses matrices and vectors for all variables and operations, with matrices indexed starting at 1. It provides functions for common math operations on matrices and vectors as well as random number generation and plotting of data.

Uploaded by

Mona Ali
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 104

MATLAB

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.

MATLAB features a family of add-on application-specific solutions called


toolboxes. Toolboxes are comprehensive collections of MATLAB functions
(M-files) that extend the MATLAB environment to solve particular classes
of problems.
Areas in which toolboxes are available include signal processing, control
systems, neural networks, fuzzy logic, wavelets, simulation, and many
others.
The name MATLAB stands for matrix laboratory.
The MATLAB system consists of five main parts:
1. Desktop Tools and Development Environment
This is the set of tools and facilities that help you use MATLAB functions
and files. Many of these tools are graphical user interfaces. It includes the
MATLAB desktop and Command Window, a command history, an editor
and debugger, a code analyzer and other reports, and browsers for
viewing help, the workspace,
files, and the search path.

2. The MATLAB Mathematical Function Library


This is a vast collection of computational algorithms ranging from
elementary functions, like sum, sine, cosine, and complex arithmetic, to
more sophisticated functions like matrix inverse, matrix Eigen values,
Bessel functions, and fast Fourier transforms.
3. The MATLAB Language
This is a high-level matrix/array language with control flow statements,
functions, data structures, input/output, and object-oriented programming
features. It allows both "programming in the small" to rapidly create quick
and dirty throw-away programs, and "programming in the large" to create
large and complex application programs.
4. Handle Graphics
Graphics MATLAB has extensive facilities for displaying vectors and matrices
as graphs, as well as annotating and printing these graphs. It includes high-
level functions for two-dimensional and three-dimensional data visualization,
image processing, animation, and presentation graphics. It also includes low-
level functions that allow you to fully customize the appearance of graphics as
well as to build complete graphical user interfaces on your MATLAB
applications.
5. The MATLAB Application Program Interface (API)
This is a library that allows you to write C and Fortran programs that interact
with MATLAB. It includes facilities for calling routines from MATLAB
(dynamic linking), calling MATLAB as a computational engine, and for
reading and writing MAT-files.
The Matlab Interface (Figure 1.1) is divided into 3 windows: The
Workspace (upper left corner) lists all defined variables and m-files
(discussed later); the Command History (lower left corner) lists the ordered
sequence of commands issued in this session; and the Command Window
(right side) is the main source of input and output of commands, variable
definitions, and errors.
In the toolbar of the interface, we can designate a directory from which to
read and to which to write m-files. It is recommended to create a new
directory (e.g. matlab) in your account, which will host any m-files,
exercises, and assignments. For simplicity, keep all Matlab related files in
this directory.
Whenever starting Matlab, change the Current Directory to this directory to
access relevant files.
Variable are formed by assigning letters or words to numbers or
expressions, as shown in Figure 1.4. All defined variables in the
Workspace can be used throughout the session.
Using variables that haven't been defined returns an appropriate error.
Declarations must follow the convention of assignment where the left side
of an equal sign is always a variable and the right side an arbitrary
expression.
Matlab handles variables by their value as opposed to symbolically. When a
variable has been assigned to a value and is used in another expression,
the variable acts as the value rather than a reference to the variable name.
We can observe this behavior in the series of expressions in Figure 1.6.
Even though c=a+b has been declared in terms of variables a and b, when
changing the value of a, c remains to be the sum of the initial a and b.
The contents of the Workspace can be cleared by issuing the command
clear . This will remove all previously defined variables.
The contents of all windows can be cleared from the Edit menu.
[x:z] defines a vector of numbers starting at x and ending at z, where each
element of the array is incremented by 1. E.g. [3:9] defines the vector
[3,4,5,6,7,8,9].
[x:y:z] defines a vector of numbers starting at x and ending at z, where each
element of the array is incremented by y. E.g. [10:2:20] defines the vector
[10,12,14,16,18,20].
Every definition explicitly returns the defined quantity, and each
expression returns a result. The output can be suppressed by ending
the expression with a ; (semicolon). E.g. a=[1:1000000] returns a
vector of 1000000 elements, a quantity that we do not necessarily
want to see element by element. The expression a=[1:1000000]; will
merely define the variable without returning unwanted output.
Figure 1.10 pictorially shows the difference between scalars and
vectors: a scalar is a single element, while a vector is a series (or a list)
of elements (of scalars).
In Figure 1.9 we have declared a scalar s and a vector t.
Having defined a vector and a scalar, we can perform arithmetic
operations. Adding (multiplying, etc.) a vector by a scalar adds
(multiplies, etc.) each element of the vector by the scalar. The result of s
* t can be assigned to an output variable u as in u = s * t . Variable u then
references the resulting vector.
Two same-sized vectors a and b are added/subtracted element-by-
element using the + and - operators, as is done in matrix addition and
subtraction. (Vectors are merely matrices with only one row).
In order to multiply two vectors element-by-element, the operator * (or /)
must be preceded by a period ., as shown in Figure 1.12.
In order to perform any element-by-element operation on two vectors,
their lengths must match, otherwise Matlab returns an error.
Figure 1.14 shows how two differently sized vectors cannot be combined
element-by-element, because there exist ambiguities as to how an
operation is defined between a scalar and a "nothing".
Besides using the range notation, vectors can also be defined by
enumerating the elements one by one (Figure 1.15). Transposing can be
accomplished by using a single quote (') after the variable name, e.g. b' .
Two same size vector can then be multiplied in matrix-terms by issuing
the command a * b' .
Figure 1.16 pictorially shows a transpose and a double transpose
operation.
Elements in a vector can be addressed individually by enclosing the
elements index in parentheses after the vector variable name, e.g. b(3) .
The vector's elements' indices start at 1 and stop at the length of the
vector. Index 0 (zero) is not used, even though it is commonly done so in
programming languages.
The command length(b) for any matrix b evaluates to the number of
elements in vector b.
A matrix is defined by rows and columns. A row of elements is delimited by
commas, e.g. 1,2,3 . Columns are delimited by semi-colons, e.g. 5;6;7 . A
matrix can thus be defined using any of the vector defining notations used
previously, e.g. [1,2,3;4,5,6;7,8,9] or [[1:3];[4:6];[7:9]] .
Figure 1.19 pictorially shows what are considered rows and columns of a
matrix, indexing conventions, and the general form of indexing into a
matrix.
Matrices of same dimensions can be added and subtracted as is defined in
matrix arithmetic. In multiplication, however, we achieve different results
depending on whether we multiply two matrices by using a*b or a.*b ,
where the latter is element-by-element multiplication.
Random numbers, vectors, and matrices can be formed using the function
rand. rand takes as arguments the number of rows, and number of columns:
rand(rows, cols) and returns a matrix of that size with random numbers
ranging from 0 to 1. The function can easily be multiplied and/or added to
scalars in order to produce random numbers in any range, e.g. a random
number between 0 and 10: rand(1,1) * 10 , or a random number between 10
and 100: (rand(1,1) * 90) + 10 .
Matrices and vectors can be appended to form larger matrices and
vectors. Given two similarly or differently sized vectors a and b, a vector c
can be formed by c=[a,b] . c is now as long as a and b combined. The
same holds for matrices. A 3x3 matrix a can be combined with a 3x5
matrix b by [a,b] but not by [a;b] , while a 3x3 matrix a can be combined
with a 5x3 matrix b by [a;b] but not by [a,b] . Depending on which way
matrices are appended, one of the dimensions (rows or columns) must
match.
Functions ceil(x) and floor(x) round decimal numbers (doubles) up and
down to the next integer, respectively. This operation can be performed on
scalars, vectors, and matrices.
Elements in a matrix can be accessed by rows and columns: A(r,c), where
A is a matrix, r is a row, and c is a column.
Rows and columns can also be accessed. To access a row in matrix A, a
colon (:) is substituted for the column, and vice versa: row_r = A(r,:) ,
column_c = A(:,c) .
The concept of indexing into a matrix
by row and column, only row, and
only column is pictorially described
in Figure 1.26.
It is also possible to extract portions of a matrix by using ranges such as [1,2] or
[1:3] as indices, as shown in Figure 1.27.
The concept of extracting sub-matrices
from matrices is shown in Figure 1.28.
Not only can we extract a sub-matrix, but we can also
replace portions of a matrix. The same form of indexing is
used, as shown in Figure 1.29.
The concept of replacing sub-
matrices is pictorially described
in Figure 1.30.
To get quick help on any Matlab function, we type help function where
function is the name of the function. help rand , for example, gives
detailed help on function rand.
To save a collection of expressions, for example for in-class exercises
and homework assignments, you will need to use m-files. M-files are no
more than simple text files that can be executed from within Matlab to
reproduce the statements in the m-file.
To create a new m-file, go to File -> New -> M-file, as shown in Figure
1.32.
We can now enter a number of statements, one statement per line. In a
later lecture, we will see how to create functions using m-files.
Save the m-file in the matlab directory which you have earlier chosen as
the Current Directory. Make sure that the extension of this file is .m, i.e.
make sure that the file ends with .m
You can now execute the statements in the m-file by typing in the name
of the m-file in the Command Window. Make sure to omit the .m
extension.
Lecture 2
2.1 Introduction - Practical Foundation - Matrices

For a practical example of using matrices, we will now look at and


manipulate multidimensional data in the form of images. Monitor screens
and images are inherently matrices with rows and columns, where each
element (pixel) can be addressed by a particular row and column index.
In Matlab, we can load a large number of image data types, including JPG,
BMP, GIF. We make use of the function misread(), which takes as an
argument the file name of the image. The image file should reside in the
Current Directory, and its name must be enclosed in single quotes, e.g.
cartman=imread('cartmancop.jpg').
To display the image we use function image(cartman) , where cartman is
the name of the variable that the loaded data has been ascribed to.
To find out the size of the loaded image data, we use function
size(cartman). Notice that size() returns 3 values: height, width, and
layers. Note: the returned valued in ans variable.
Using the general matrix indexing conventions, we can extract a portion of
the image and display it: image(cartman([170:193],:,:)); where [170:193] is
a range of rows to extract, and the 2 following colons (:) denote "all
columns", and "all layers", respectively. (open at figure1)
Figure below shows another example of sub-matrix extraction:
image(cartman([1:130],[45:200],:)); . Here we extract a specific range of
rows AND columns, while still extracting all layers.
Multiplying the image matrix by a scalar greater than 1 increases the
combination of brightness and contrast of the image:
image(uint8(double(cartman(:,:,:)) * 2));
The command: converts the image data to type double; increases
brightness/contrast; converts the data back to uint8; and displays the
image.
Multiplying the image data by a number less than 1 decreases
brightness/contrast of the image.
Figure below shows an example in which a portion of the image matrix is
replaced. In this example, the replacement sub-matrix comes from the
same image matrix, only that its brightness/contrast is increased:
cartman([170:193],:,:) = uint8(double(cartman([170:193],:,:))*2);
2.2 Introduction - Practial Foundation - Vectors

For a practical example using vectors, we will now look at a one


dimensional data structure, namely sound. A sound wave is merely a
collection of values that, when graphed in the x/y plane, exhibits a large
number of sine waves at different heights (amplitudes) and different
periods.
To load a wave sound file, we issue the command:
authoritah=wavread('authoritah.wav');
Analogous to function misread, wavread returns the content of the wave
file in terms of numbers. In the previous command, this vector of numbers
is assigned to variable authoritah.
We can play back the sound file by issuing the command:
wavplay(authoritah) . Note that the file is played back too fast, i.e. at a
higher frequency than what the file was recorded in. To change the
playback frequency, we merely pass the correct frequency to the function:
wavplay(authoritah, 8000) . The sound file is now played back at
frequency 8000 Hz = 8 KHz.
Just as we have evaluated the size of the image, we can find out the size
of this sound file: size(authoritah) . This sound file is a data structure of
size 16565*1, which essentially means that it is a vector with 16565
elements.
When plotting the wave form with plot(authoritah) , we can roughly make
out words and syllables by the concentrated high amplitudes.
While multiplication of an image with a scalar resulted in a change in
brightness/contrast, multiplication of a wave form with a scalar results in a
change of amplitude (volume). Since the data type of the wave form vector
is double, we need not convert it:
authoritahAmp = authoritah*4;
wavplay(authoritahAmp, 8000);
plot(authoritahAmp);
We can extract portions of the wave form by indexing into the vector, e.g.
the individual words:
wordYou=authoritah(1:2400);
wordWill=authoritah(2000:4400);
wordRespect=authoritah(4500:8000);
wordMy=authoritah(8000:9000);
wordAuthoritah=authoritah(9800: length(authoritah));
and then play and plot them, e.g.:
wavplay(wordAuthoritah, 8000);
plot(wordAuthoritah);
Once all of the words have been isolated from the sound file, they can be
re-ordered to form a new, while not necessarily senseful sentence:
authoritah2=[wordMy; wordAuthoritah; wordWill; wordRespect; wordYou];
wavplay(authoritah2, 8000);
plot(authoritah2);
Try to plot other vectors, wordMy, wordWill, etc.
Finally, we can generate primitive wave forms, e.g. a beep, by repeating
a sine wave of some constant period:
beepsound1=sin([0:0.3:pi*2000]);
wavplay(beepsound1, 8000);
Plot(beepsound1);
Lecture 3
3.1 Loops
for loops
The "for" loop is used in a scenarios in which the range over which the loop
iterates is strictly defined.
for i=1:10 i^2 end

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;

Note: try i<=3, etc


3.2 Loops - Examples
3.2.1 Color Gradient
we will build a one dimensional image in which one color fades into
another (fade black into red).
Since we intend to generate a one dimensional image, we require one row
with several columns (each column of which will take a different color),
and 3 colors each (Red, Green, and Blue), which will be dimmed
selectively.
grad=[ ];
creates a new matrix in Matlab - we need not specify the final dimensions
for i=1:255
grad(1,i,1)=i;
grad(1,i,2)=0;
grad(1,i,3)=0;
end

The first line defines the image intensity (256)


The three lines in the body of the loop define each of Red, Green, and Blue.
Green and Blue are set to 0, Red is set to i because the loop happens to iterate
over all possible intensities.
Next slide display the image.
The image can be displayed by converting it to uint8 and calling function
image():
image(uint8(grad));

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));

Since loop variable j iterates over columns, we can use it as a factor of


brightness/contrast. Since we use 70/j as a factor for each color channel,
the first 69 pixels of each row increase in brightness/contrast (denominator
is smaller than numerator), while all pixels > 70 decrease in brightness.
Additionally, we use loop variable i to increase brightness with increasing
row number.
Lecture 4
4.1 Conditionals
Simple if statement
if expression
(commands)
end
>> x = 10;
>> if x == 10
disp ('ok')
end;

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);

The conditional in this


example tests whether or
not a color value is below
the threshold of 120, and if
this condition holds then
the intensity is set to 0.
Instead of setting the intensity to 0, we could also set it to 255 for a
different effect.

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);

Plotted in regular (default) scale assigns each data point to a


proportionally increasing (+ 1) x value:
For example, consider the following data points:

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);

Given a different data range corresponding to the same y-data the


graph exhibits distinct differences.
String modifiers can be used to change color, data point, and line styles. A
summary is given in table below.
Colors Point style Line style
b blue . point - solid
g green o circle : dotted
r red x x-mark -. dashdot
c cyan + plus -- dashed
m magenta * star (none) no line
y yellow s square
k black d diamond
v triangle (down)
^ triangle (up)
< triangle (left)
> triangle (right)
p pentagram
h hexagram

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');

Try this command


plot(x,y,'g:');

Try this command


plot(x,y,'md:');

A figure's background color can be changed using the command whitebg .


For example:

whitebg('k')

Try this command


whitebg('y')
5.1.1 Bar Charts
2D bar graphs plot data points in terms of their area. Given some random
data:

xBar=[1:10];
yBar=rand(1,10) * 100;

a bar chart is produced using:


bar(xBar,yBar);
2D bar charts can also be created for matrices, in which case each row in
the matrix is considered as one group of bars. The resulting graph
distinguishes matrix columns with different colors.

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:

plot(x, y, 'r*-.'), xlabel('South'), ylabel('West)


A title is added by using the command title :

plot(x, y, 'r*-.'), xlabel('South'), ylabel('West'),


title('Mysterious Constellation of a Waiving Hand');
By default, the data range of x is used for labeling individual tick
marks on the x-axis. Alternatively, named values can be used as
replacements.
x=1:8;
y=rand(1,8) * 100;
plot(x,y);
set(gca, 'XTickLabel', {'Earth', 'Mercure', 'Saturn', 'Venus', 'Pluto',
'Neptune', 'Mars', 'Jupiter'})
5.1.3 Overlaying plots
Several plots can be placed in the same figure by overlaying them.
The simplest approach is to plot a matrix of values, in which each
column is interpreted as one vector.

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);

creates a mesh (with holes)


Try these commands

[X,Y] = meshgrid(-3:.125:3);
Z = peaks(X,Y);
meshc(X,Y,Z);
axis([-3 3 -3 3 -10 5])

Try these commands

[X,Y] = meshgrid(-3:.125:3);
Z = peaks(X,Y);
meshz(X,Y,Z)
surf(z);

creates a mesh with filled patches (a surface).

You might also like