0% found this document useful (0 votes)
26 views

Lecture 001

This document discusses MATLAB, an interactive system for technical computing. MATLAB can be used for math, modeling, data analysis and visualization. It allows matrix operations to be done easily. The document covers basic MATLAB operations like manipulating matrices, using functions and creating M-files.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Lecture 001

This document discusses MATLAB, an interactive system for technical computing. MATLAB can be used for math, modeling, data analysis and visualization. It allows matrix operations to be done easily. The document covers basic MATLAB operations like manipulating matrices, using functions and creating M-files.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

TME 214

Elementary Computer Programming

Dr A.S. Adebayo
Mechanical Engineering Department
University of Ibadan 1
Essentials of MATLAB
Programming
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.
What Is MATLAB?
Cont…
Typical uses include:
 Math and computation
 Algorithm development
 Modeling, simulation, and prototyping
 Data analysis, exploration, and visualization
 Scientific and engineering graphics
 Application development, including graphical
user interface building
What Is MATLAB?
Cont…

 MATLAB is an interactive system whose


basic data element is an array that does not
require dimensioning.
 This allows you to solve many technical
computing problems, especially those with
matrix and vector formulations, in a fraction
of the time it would take to write a program
in a scalar noninteractive language such as
C or Fortran.
What Is MATLAB?
Cont….
 The name MATLAB stands for matrix
laboratory. MATLAB was originally written
to provide easy access to matrix software
developed by the LINPACK and EISPACK
projects.

 Today, MATLAB uses software developed


by the LAPACK and ARPACK projects,
which together represent the state-of-the-
art in software for matrix computation.
What Is MATLAB?
Cont….
 MATLAB has evolved over a period of
years with input from many users. In
university environments, it is the standard
instructional tool for introductory and
advanced courses in mathematics,
engineering, and science.
 In industry, MATLAB is the tool of choice
for high-productivity research,
development, and analysis.
What Is MATLAB?
Cont….
 MATLAB features a family of application-specific
solutions called toolboxes. Very important to most
users of MATLAB, toolboxes allow you to learn
and apply specialized technology.
 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.
MATLAB Desktop
Command Window

Use the Command Window to enter


variables and run functions and M-files.
Command History

Lines you enter in the Command Window


are logged in the Command History
window. In the Command History, you can
view previously used functions, and copy
and execute selected lines.
Current Directory
Browser

MATLAB file operations use the current


directory and the search path as reference
points. Any file you want to run must either
be in the current directory or on the search
path.
Workspace Browser

The MATLAB workspace consists of the


set of variables (named arrays) built up
during a MATLAB session and stored in
memory. You add variables to the
workspace by using functions, running M-
files, and loading saved workspaces.
Manipulating Matrices in
MATLAB
You can enter matrices into MATLAB in
several different ways:
 Enter an explicit list of elements.
 Load matrices from external data files.
 Generate matrices using built-in functions.
 Create matrices with your own functions in
M-files.
Basic conventions of
entering matrices elements
 Separate the elements of a row with blanks or
commas.
 Use a semicolon ‘ ;’ to indicate the end of each
row.
 Surround the entire list of elements with square
brackets, [ ].
To enter Dürer’s matrix, simply type in the
Command Window
A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]
Manipulating Matrices
Cont…
sum, transpose, and diag of matrices:
To find the sum along any row, column and
diagonal
Enter in the Command windrow
For column sum: sum(A)
For row sum: sum(A`)
For diagonal sum: sum(diag(A))
Manipulating Matrices
Cont…
Subscripts
The element in row i and column j of A is
denoted by A(i,j). For example, A(4,2) is
the number in the fourth row and second
column.
Manipulating Matrices
Cont…
 It is also possible to refer to the elements of a
matrix with a single subscript, A(k). This is the
usual way of referencing row and column vectors.
 But it can also apply to a fully two-dimensional
matrix, in which case the array is regarded as one
long column vector formed from the columns of
the original matrix.
 So, for our magic square, A(8) is another way of
referring to the value 15 stored in A(4,2).
Manipulating Matrices
Cont…
The Colon Operator
The colon, :, is one of MATLAB’s most important
operators. It occurs in several different forms.

The expression 1:10 is a row vector containing the


integers from 1 to 10
1 2 3 4 5 6 7 8 9 10
To obtain nonunit spacing, specify an increment.
For example, 100:-7:50
is
100 93 86 79 72 65 58 51
Manipulating Matrices
Cont…
The magic Function
MATLAB actually has a built-in function that creates
magic squares of almost any size. Not surprisingly,
this function is named magic.
B = magic(4)
B=
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
Expressions in MATLAB

Like most other programming languages,


MATLAB provides mathematical
expressions, but unlike most programming
languages, these expressions involve entire
matrices.
The building blocks of expressions are:
 Variables
 Numbers
 Operators
 Functions
Variables

MATLAB does not require any type


declarations or dimension statements. When
MATLAB encounters a new variable name, it
automatically creates the variable and
allocates the appropriate amount of storage. If
the variable already exists, MATLAB changes
its contents and, if necessary, allocates new
storage.
For example,
num_students = 25
Numbers

MATLAB uses conventional decimal notation,


with an optional decimal point and leading plus
or minus sign, for numbers. Scientific notation
uses the letter e to specify a power-of-ten scale
factor. Imaginary numbers use either i or j as a
suffix.
Some examples of legal numbers are
3 -99 0.0001
Operators
Expressions use familiar arithmetic operators
and precedence rules.
+ Addition
- Subtraction
* Multiplication
/ Division
\ Left division (described in “Matrices and Linear Algebra” in Using MATLAB)
^ Power
' Complex conjugate transpose
( ) Specify evaluation order
Functions

MATLAB provides a large number of


standard elementary mathematical
functions, including abs, sqrt, exp, and sin.
M-Files
You can create your own matrices using M-files, which
are text files containing MATLAB code. Use the
MATLAB Editor or another text editor to create a file
containing the same statements you would type at the
MATLAB command line. Save the file under a name
that ends in ‘.m’ extension
For example, create a file containing these five lines.
A = [ ...
16.0 3.0 2.0 13.0
5.0 10.0 11.0 8.0
9.0 6.0 7.0 12.0
Concatenation
Concatenation is the process of joining small
matrices to make bigger ones. In fact, you
made your first matrix by concatenating its
individual elements. The pair of square
brackets, [], is the concatenation operator.

For an example, start with the 4-by-4 magic


square, A, and form
B = [A A+32; A+48 A+16]
The result is an 8-by-8 matrix, obtained by
joining the four submatrices.
B=
16 3 2 13 48 35 34 45
5 10 11 8 37 42 43 40
9 6 7 12 41 38 39 44
4 15 14 1 36 47 46 33
64 51 50 61 32 19 18 29
53 58 59 56 21 26 27 24
57 54 55 60 25 22 23 28
52 63 62 49 20 31 30 17
Deleting Rows and
Columns
You can delete rows and columns from a matrix using
just a pair of square brackets. Start with
X = A;
Then, to delete the second column of X, use
X(:,2) = [ ]

This reduces X to
X=
16 2 13
5 11 8
9 7 12
4 14 1
Arrays
Matrices are two dimensional numeric
arrays. Arithmetic operations on arrays are
done element-by-element. This means
that addition and subtraction are the same
for arrays and matrices, but that
multiplicative operations are different.
MATLAB uses a dot, or decimal point, as
part of the notation for multiplicative array
operations.
The list of operators
includes:
+ Addition
- Subtraction
.* Element-by-element multiplication
./ Element-by-element division
.\ Element-by-element left division
.^ Element-by-element power
.' Unconjugated array transpose
Suppressing Output

If you simply type a statement and press


Return or Enter, MATLAB automatically
displays the results on screen. However, if you
end the line with a semicolon ‘;’, MATLAB
performs the computation but does not display
any output. This is particularly useful when you
generate large matrices.
For example,
A = magic(100);
Entering Long Command Lines

If a statement does not fit on one line, use


three periods, ..., followed by Return or
Enter to indicate that the statement
continues on the next line.
For example,
s = 1 -1/2 + 1/3 -1/4 + 1/5 - 1/6 + 1/7 ...
- 1/8 + 1/9 - 1/10 + 1/11 - 1/12;
Random number generator
To generate random numbers use the MATLAB
function ‘rand’ For uniformly distributed
pseudorandom numbers
Syntax
Y = rand
Y = rand(n)
Y = rand(m,n)
Y= rand([m n])
Y = rand(m,n,p,...)
Y = rand([m n p...])
Y = rand(size(A))
rand(method,s)
s = rand(method)
Example
Generate a uniform distribution of random
numbers on a specified interval [a,b]. To do
this, multiply the output of rand by (b-a), then
add a.

For example, to generate a 5-by-5 array of


uniformly distributed random numbers on the
interval [10,50],a = 10; b = 50;

x = a + (b-a) * rand(5)
Result
x=
19.1591 49.8454 10.1854 25.9913 17.2739
46.5335 13.1270 40.9964 20.3948 20.5521
16.0951 27.7071 42.6921 42.0027 15.8216
43.0327 14.2661 44.7478 27.2566 15.4427
31.5337 48.4759 13.3774 46.4259 44.7717
Random number generator

Random numbers can be generated


based on other distributions
Binomial random numbers
For example, consider binomial random
numbers. You can think of a binomial random
number as the number of heads in N tosses of a
coin with probability p of a heads on any toss.
If you generate N uniform random numbers on
the interval (0,1) and count the number less than
p, then the count is a binomial random number
with parameters N and p.
Example

The following function is a simple implementation of a


binomial RNG using this approach:

function X = directbinornd(N,p,m,n)
X = zeros(m,n); % Preallocate memory
for i = 1:m*n
u = rand(N,1);
X(i) = sum(u < p);
End

For example,
X = directbinornd(100,0.3,1e4,1);
For example, the following code generates
random numbers from a specific
exponential distribution using the inverse
cdf and the MATLAB uniform random
number generator rand:
mu = 1;
X = expinv(rand(1e4,1),mu);
Basic Plotting
MATLAB has extensive facilities for displaying
vectors and matrices as graphs, as well as
annotating and printing these graphs.

The ‘plot’ function has different forms,


depending on the input arguments. If y is a
vector, plot(y) produces a piecewise linear
graph of the elements of y versus the index of
the elements of y. If you specify two vectors as
arguments, plot(x,y) produces a graph of y
versus x.
Example
these statements use the colon operator to create a
vector of x values ranging from zero to 2pi, compute
the sine of these values, and plot the result.
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)

Now label the axes and add a title. The characters \pi
create the symbol pi.
xlabel('x = 0:2\pi')
ylabel('Sine of x')
title('Plot of the Sine Function','FontSize',12)
Result
Multiple Data Sets in One
Graph
For example, these statements plot three related
functions of x, each curve in a separate
distinguishing color.
y2 = sin(x-.25);
y3 = sin(x-.5);
plot(x,y,x,y2,x,y3)
The legend command provides an easy way to
identify the individual plots.
 legend('sin(x)','sin(x-.25)','sin(x-.5)')
Result
Specifying Line Styles
and Colors

It is possible to specify color, line styles, and


markers (such as plus signs or circles)
when you plot your data using the plot
command.
plot(x,y,'color_style_marker')
color_style_marker is a string containing
from one to four characters (enclosed in
single quotation marks) constructed from a
color, a line style, and a marker type:
color_style_marker codes
•Color strings are 'c', 'm', 'y', 'r', 'g', 'b', 'w', and 'k'.
These correspond to cyan, magenta, yellow, red,
green, blue, white, and black.
•Linestyle strings are '-' for solid, '--' for dashed, ':'
for dotted, '-.' for dash-dot. Omit the linestyle for
no line.
•The marker types are '+', 'o', '*', and 'x' and the
filled marker types 's‘ for square, 'd' for diamond,
'^' for up triangle, 'v' for down triangle, '>‘for right
triangle, '<' for left triangle, 'p' for pentagram, 'h'
for hexagram, and none for no marker.
Mesh and Surface Plots
MATLAB defines a surface by the z-coordinates
of points above a grid in the x-y plane, using
straight lines to connect adjacent points. The
mesh and surf plotting functions display
surfaces in three dimensions.
‘mesh’ produces wireframe surfaces that color
only the lines connecting the defining points.
‘surf’ displays both the connecting lines and the
faces of the surface in color.
Example – Graphing the
sinc Function
The graphs the two-dimensional sinc function, sin(r)/r,
between the x and y directions. R is the distance from
origin, which is at the center of the matrix. Adding eps (a
MATLAB command that returns the smallest floating-
point number on your system) avoids the indeterminate
0/0 at the origin.

[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R;
mesh(X,Y,Z,'EdgeColor','black')
Results
Example Colored
Surface Plots
A surface plot is similar to a mesh plot except the rectangular
faces of the surface are colored. The color of the faces is
determined by the values of Z and the colormap (a
colormap is an ordered list of colors). These statements
graph the sinc function as a surface plot, select a
colormap, and add a color bar to show the mapping of
data to color.

surf(X,Y,Z)
colormap hsv
colorbar
Result

You might also like