Chapter 1 - Basic Programming, Matrices and Arrays, Functions, Plotting, 2D, 3D
Chapter 1 - Basic Programming, Matrices and Arrays, Functions, Plotting, 2D, 3D
CUK
• Assessment:
o Lab Assignment/Exercises/Takeaway– 30%
o End Semester Exam – 70%
Basic Programming
in MATLAB
Introd. to MATLAB Environment
• Advantages:
– Handles vector and matrices very nice
– Quick plotting and analysis
– EXTENSIVE documentation (type “help”)
– Lots of nice functions: FFT, fuzzy logic, neural nets,
numerical integration, OpenGL
• Drawbacks:
– Slow compared to C or Java
MATLAB is not:
❑ not a computer algebra system
❑ not a strong general purpose programming language
• limited support for other data structures
• few software-engineering features;
typical MATLAB programs are only a few lines long
• not well-suited for teaching OOP
• limited GUI features
❑ not a high-performance language (but fast matrix operators)
❑ not freely available (but local campus license)
Introd. to MATLAB Environment
• Arithmetic
– numeric computations, e.g., 2^10
• Relational
– quantitative comparison of operands
– e.g., a < b
• Logical
– AND, OR, NOT
return Boolean variable, 1 (TRUE) or 0 (FALSE)
Arithmetic Operators
MATLAB Relational Operators
» a=5;
» b=a/2
b=
2.5000
»
Other MATLAB symbols
>> prompt
... continue statement on next line
, separate statements and data
% start comment which ends at end of line
; (1) suppress output
(2) used as a row separator in a matrix
: specify range
MATLAB Matrices
colvec =
13
45
-2
MATLAB Matrices
» matrix = [1 , 2 , 3 ; 4 , 5 ,6 ; 7 , 8 , 9]
matrix =
1 2 3
4 5 6
7 8 9
MATLAB matrices
Generate a “magic square” with equal row/column/diagonal
sums and assign the resulting 3 × 3 matrix to variable a:
>> a= magic(3)
a =
8
3 1 6
4 5 7
9 2
Colon generates number sequence: Specify step size with second colon:
>> 11:14 >> 1:3:12
ans = ans =
11 12 13 14 1 4 7 10
» matrix=[1,2,3;4,5,6;7,8,9] » col_two=matrix( : , 2)
col_two =
matrix =
2
1 2 3 5
4 5 6 8
7 8 9
MATLAB Matrices
• A row vector can be • Here we extract row 2 of
extracted from a matrix. the matrix and make a row
As an example we create vector. Note that the 2:2
a matrix below: specifies the second row
and the 1:3 specifies
» matrix=[1,2,3;4,5,6;7,8,9] which columns of the row.
matrix = » rowvec=matrix(2 : 2 , 1 : 3)
1 2 3 rowvec =
4 5 6
7 8 9 4 5 6
Matlab Selection Structures
if expression1 % is true
% execute these commands
elseif expression2 % is true
% execute these commands
else % the default
% execute these commands
end
MATLAB Repetition Structures
» a=3;
» b=[1, 2, 3;4, 5, 6]
b=
1 2 3
4 5 6
» c= b+a % Add a to each element of b
c=
4 5 6
7 8 9
Scalar - Matrix Subtraction
» a=3;
» b=[1, 2, 3;4, 5, 6]
b=
1 2 3
4 5 6
» c = b - a %Subtract a from each element of b
c=
-2 -1 0
1 2 3
Matrix multiplication (dot product)
• • • • • • •
• • • • • • • • • • •
• • • · • • • • = • • • •
• • • • • • • • • • •
• • • • • • •
• • • •
• • • •
• • • •
·
• • • • • • •
• • • • • • •
• • • = • • • •
• • • • • • •
• • • • • • •
• • • •
• • • •
• • • •
· k
• • • • • • •
• • • • • • •
• • • • • • •
• • • • • • •
• • • • • • •
• • • •
• • • •
• • • •
· k
• • • • • • •
• • • • • • •
• • • • • • •
• • • • • • •
• • • • • • •
• • • •
• • • •
• • • •
· k
• • • • • • •
• • • • • • •
• • • • • • •
• • • • • • •
• • • • • • •
• • • •
• • • •
• • • •
· k
• • • • • • •
• • • • • • •
• • • • • • •
• • • • • • •
• • • • • • •
» a=3;
» b=[1, 2, 3; 4, 5, 6]
b=
1 2 3
4 5 6
» c = a * b % Multiply each element of b by a
c=
3 6 9
12 15 18
Scalar - Matrix Division
» a=3;
» b=[1, 2, 3; 4, 5, 6]
b=
1 2 3
4 5 6
»c=b/a % Divide each element of b by a
c=
0.3333 0.6667 1.0000
1.3333 1.6667 2.0000
Mathematical Functions
Inbuilt functions:
• sin(x) cos(x) tan(x) exp(x)
• asin(x) acos(x) atan(x) log(x),log10(x)
• sinh(x) cosh(x) tanh(x) sqrt(x) = xˆ(1/2)
• real(x) imag(x) mod(a,b) factorial(n)
Trigonometric functions (Radian)
Trigonometric functions (degree)
Hyperbolic functions
Example:
• hyperbolic functions f(x) = sinh x, f(x) = cosh x and f(x) =
tanh x.
• hyperbolic functions cosh x and sinh x are defined using
the exponential function ⅇ𝑥 .
Complex functions
.
Examples 1:
• Define a function in a file named average.m that accepts
an input vector, calculates the average of the values, and
returns a single result .
Plotting
• Some Commonly used plotting Commands (1)
o axis Sets axis limits.
o fplot Intelligent plotting of functions.
o grid Displays gridlines.
o plot Generates xy plot.
o print Prints plot or saves plot to a file.
o title Puts text at top of plot.
o xlabel Adds text label to x-axis.
o ylabel Adds text label to y-axis.
o axes Creates axes objects.
o close Closes the current plot.
o close all Closes all plots.
o figure Opens a new figure window.
o gtext Enables label placement by mouse.
o hold Freezes current plot.
o legend Legend placement by mouse.
o refresh Redraws current figure window.
o set Specifies properties of objects such as axes.
o subplot Creates plots in sub windows.
o text Places string in figure.
o bar Creates bar chart.
o loglog Creates log-log plot.
o polar Creates polar plot.
o semilogx Creates semi log plot. (logarithmic abscissa).
o semilogy Creates semi log plot. (logarithmic ordinate).
o stairs Creates stairs plot.
o stem Creates stem plot.
• Other Useful MATLAB commands
o who List known variables
o whos List known variables plus their size
o help Ex: >> help sqrt Help on using sqrt
o clear Clear all variables from work space
o clear x y Clear variables x and y from work space
o clc Clear the command window
o what List all m-files in current directory
o dir / ls List all files in current directory
o type test Display test.m in command window
o delete test Delete test.m
o cd a: chdir a: Change directory to a:
o pwd Show current directory
• Reading Data from files
• MATLAB supports reading an entire file and creating a matrix
of the data with one statement.
>> load mydata.dat; % loads file into matrix.
% The matrix may be a scalar, a vector, or a
% matrix with multiple rows and columns. The
% matrix will be named mydata.
>> size (mydata) % size will return the number
% of rows and number of
% columns in the matrix
>> length (myvector) % length will return the total
% no. of elements in myvector
• Plotting with MATLAB (1)
• MATLAB will plot one vector vs. another. The first one will
be treated as the abscissa (or x) vector and the second as
the ordinate (or y) vector. The vectors have to be the
same length.
• MATLAB will also plot a vector vs. its own index. Given a
vector “time” and a vector “dist” we could say:
>> plot (time, dist) % plotting versus time
>> plot (dist) % plotting versus index
• Plotting with MATLAB (2)
0.8
0.6
0.6 0.4
0.2
0.4
0
0.2 -0.2
-0.4
0 0 2 4 6 8
0 5 10 15 20 10
x = 0:20; t = 0:0.1:10;
y = 0.5 - 0.5*cos(2*pi * x/20); x = exp(t * (j - 1/3));
stem(x, y); plot(t, real(x), t, imag(x));
title('20-point raised cosine'); grid; legend('real', 'imaginary')
Only the function that has the same name as the m-file in which it
is defined can be called from outside the file; all other functions
are only visible inside the file. The function keyword sets the
variable whose value will be returned and lists the parameter
variables.
The m-file must be in the current directory (cd) or MATLAB's search
path (path) to become accessible.
Use edit db to edit the m-file, help db to show the first comment lines and
type db to show its source text.
M-files can also contain just sequences of statements instead of a
function definition. These are called simply by typing their name.
Recursion (1)
• Recursion is a repetitive process in which a function calls itself. The
process of repetition can be done in 2 ways using programming:
o Iterative Definition
o Recursive Definition
• Iterative : Repeating a set of statements using loops
• Recursive: A repetitive function is defined recursively whenever
the function appears within the definition itself. E.g. factorial of a no
4! =4x3x2x1; if n is the number then
n!= nx(n-1)x(n-2)x(n-3)x(n-4)……x(n-n)
n!=nx(n-1)!
(n-1)!=(n-1) x (n-2)!
(n-2)!=(n-2)x(n-3)!
……………………………………
(n-n)!=1 (0!, 1! =1)
Recursion (2)
• The recursive function has two elements : each call either
solves one part of the problem or it reduces the size of the
problem. The statement that solves the problem is known as
the base case. The rest of the function is known as the
general case. Each recursive function must have a base
case.
n=nx(n-1)! Is the general case as it is valid for all n values
n!=1 is considered as base case
• Base case: factorial(0)
• General case: nxfactorial(n-1).
Recursion (3)
• The following are the rules for designing a recursive function:
1. First, determine the base case
2. Then, determine the general case
3. Finally, combine the base case and general case into a function
• Matlab Syntax:
f = factorial(n) e.g. f = factorial(10) ; f=3628800
Factorial of an Array elements:
n = [0 1 2; 3 4 5]; f = factorial(n)
f = 2×3
1 1 2
6 24 120
Iterations (1)
• We can use iterations to get the multiplication of numbers
n=9
% use iterations
f = 1;
for i = 1:n
f = f*i;
end
f
Also
n=input('the value of n: ');
f=1;
for i=1:n
f=f*i;
end
disp('factorial is')
disp(f)