Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 66

Introduction to Matlab

Eng. Michael J. Shundi (PEng (T))


Phone : +255 620 255728
Email: kakamika100@gmail.com
Website: https://kakamika-snr.github.io/tza/
Outline:
 What is Matlab?
 Matlab GUI
 Variables, array, matrix, indexing
 Operators (Arithmetic, relational, logical )
 Plots in Matlab
 Display Facilities
 Flow Control
 Using of M-File
 Writing User Defined Functions
 Conclusion
What is Matlab?
 Matlab is basically a high level language
which has many specialized toolboxes for
making things easier for us
 How high?
Matlab

High Level
Languages such as
C, Pascal etc.

Assembly
Matlab
MATLAB stands for Matrix Laboratory.
Matlab has many functions and toolboxes to
help in various applications
It allows you to solve many technical
computing problems, especially those with
matrix and vector formulas,
MATLAB’s Features

 Main Features
 Simple programming rules
 Extended accuracy
 Continuity among integer, real and complex
values
 Comprehensive mathematical library
 Extensive graphics tools
 Linkages with other languages
 Transportability across environment
 MATLAB scripts will work on PC, UNIX, Mac
Matlab GUI
 Command Window
 type commands

 Current Directory
 View folders and m-files

 Workspace
 View program variables
 Double click on a variable
to see it in the Array Editor

 Command History
 view past commands
 save a whole session
using diary
MATLAB GUI
 Workspace Window
 Shows all currently defined variables
 Array dimensions
 Min, max values
 Good debugging tool
 Command History
 Shows all past commands
 Can copy and past commands into
command window
 Double click will execute command
MATLAB GUI

 Desktop Menus
 File Menu
 New
 Create new MATLAB
program file (m-file)
 Open existing m-file
 Import data
 Set Path
 Open recent m-files
MATLAB GUI

 Edit Menu
 Copy, cut, paste
 Find and replace
phrases
 Clear command
history, workspace
 Desktop Menu
 Change
appearance of
desktop
 Select windows to
display
MATLAB’s Commands

 Enter commands at >> prompt

 Variable ‘x’ automatically allocated


 MATLAB does not require declaration of variables
 Nice, but can get you in trouble so be careful
MATLAB’s Commands
 MATLAB is case sensitive
 Variable ‘ans’ will take value of
result of command if no equal sign
specified
 Holds most recent result only
 Semicolon at end of line will
suppress output, it is not required
like in C
 Useful in script files and debugging
MATLAB’s Commands

 Format of output
 Defaults to 4 decimal places
 Can change using format statement

 format long changes

output to 15 decimal places


 format short changes back

to 4 decimal places
Variables

 As MATLAB is case sensitive


 X is not equal to x
 Variable names must start
with a letter
 You’ll get an error if this doesn’t
happen
 After that, can be any
combination of letters, numbers
and underscores
 No special characters though
Variables

 Don’t name your variables the same as


functions
 min, max, sqrt, cos, sin, tan, mean, median, etc
 Funny things happen when you do this
 MATLAB reserved words don’t work either
 i, j, eps, nargin, end, pi, date, etc
 i, j are reserved as complex numbers initially
 Will work as counters in my experience so they can be
redefined as real numbers
Variables
 No need for types. i.e.,

int a;
double b;
float c;

 All variables are created with double precision unless


specified and they are matrices.
Example:
>>x=5;
>>x1=2;

 After these statements, the variables are 1x1 matrices


with double precision
Array, Matrix
 a vector x = [1 2 5 1]

x =
1 2 5 1

 a matrix x = [1 2 3; 5 1 4; 3 2 -1]

x =
1 2 3
5 1 4
3 2 -1 Apostrophe symbol

 transpose y = x’ y =
1
2
5
1
Long Array, Matrix
By default step size is “1” in matlab,
 t =1:10
you can modify it as your requirement.
t =
1 2 3 4 5 6 7 8 9 10
 k =1:0.5:5

k =
1 1.5 2 2.5 3 3.5 4 4.5 5

 B = [1:4; 5:8]

x =
1 2 3 4
5 6 7 8
Generating Vectors from functions
 zeros(M,N) MxN matrix of zeros x = zeros(1,3)
x =
0 0 0

 ones(M,N) MxN matrix of ones


x = ones(1,3)
x =
1 1 1
 rand(M,N) MxN matrix of uniformly
distributed random x = rand(1,3)
numbers on (0,1) x =
0.9501 0.2311 0.6068
Operators (arithmetic)
+ addition
- subtraction
* multiplication
/ division
^ power
‘ complex conjugate transpose
Operators
 Scalar arithmetic operations
Operation MATLAB form
 Exponentiation: ^ ab a^b
 Multiplication: * ab a*b
 Right Division: / a / b = a/b a/b
 Left Division: \ a \ b = b/a a\b
 Addition: + a+b a+b
 Subtraction: - a–b a-b
 MATLAB will ignore white space between
variables and operators
Order of Operations
 Parentheses
 Exponentiation
 Multiplication and division have equal
precedence
 Addition and subtraction have equal
precedence
 Evaluation occurs from left to right
 When in doubt, use parentheses
 MATLAB will help match parentheses for you
Operators (relational, logical)
 == Equal to
 ~= Not equal to
 < Strictly smaller
 > Strictly greater
 <= Smaller than or equal to
 >= Greater than or equal to
 & And operator
 | Or operator
The Matrix in MATLAB

Columns
(n)
1 2 3 4 5
A= 4
1
10
6
1
11
6
16
2
21
A (2,4)
1
2
2 8 1.2 7 9 12
4 17
25 22

Rows (m) 3 7.2 3 5 8


7 13
1 18
11 23 A (17)
4 0 4
0.5 9 4 14
5 19
56 24
Rectangular Matrix:
5 10 15 20 25
5 23 83 13 0 10 Scalar: 1-by-1 array
Vector: m-by-1 array
1-by-n array
Matrix elements can be EITHER
Matrix: m-by-n array
numbers OR characters
Matrix Index
 The matrix indices begin from 1 (not 0 (as in C))
 The matrix indices must be positive integer
Given:

A(-2), A(0)

Error: ??? Subscript indices must either be real positive integers or logicals.

A(4,2)
Error: ??? Index exceeds matrix dimensions.
Concatenation of Matrices
 x = [1 2], y = [4 5], z=[ 0 0]

A = [ x y]
Horizontal concatenation
1 2 4 5

B = [x ; y]
Vertical concatenation
1 2
4 5

C = [x y ;z]
Error:
??? Error using ==> vertcat CAT arguments dimensions are not consistent.
Matrices Operations

Given A and B:

Addition Subtraction Product Transpose


Operators (Element by Element)

.* element-by-element multiplication
./ element-by-element division
.^ element-by-element power
The use of “.” – “Element” Operation
A = [1 2 3; 5 1 4; 3 2 1]
A=
1 2 3
5 1 4
3 2 1

b = x .* y c=x./y d = x .^2
x = A(1,:) y = A(3 ,:)
b= c= d=
x= y= 3 4 3 0.33 1 3 1 4 9
1 2 3 3 2 1
K= x^2
Erorr:
??? Error using ==> mpower Matrix must be square.
B=x*y
Erorr:
??? Error using ==> mtimes Inner matrix dimensions must agree.
Matrix Multiplication
Inner dimensions must be equal
Dimension of resulting matrix = outermost
dimensions of multiplied matrices
Resulting elements = dot product of the rows of
the 1st matrix with the columns of the 2nd
matrix
» a = [1 2 3 4; 5 6 7 8]; [2x4]
» b = ones(4,3); [4x3]
» c = a*b [2x4]*[4x3] [2x3]
c =
10 10 10
26 26 26 a(2nd row).b(3rd column)
Inverse of Matrix

 Inverse of matix can be calculated in a


fraction of time
 If A is 3x3 or higher dimension matrix,

inverse of matrix = inv(A)


Determinant of Matrix

 Determinant of matix can also be calculated


in a fraction of time
 If A is 3x3 or higher dimension matrix,

determinant of matrix = det(A)


Example: Solving Equations

Solve this set of simultaneous equations:


» A = [-1 1 2; 3 -1 1;-1 3 4];
» b = [2;6;4];
» x = inv(A)*b
x =
-x1 + x2 + 2x3 = 2
1.0000
-1.0000
3x1 - x2 + x3 = 6
2.0000
-x1 + 3x2 + 4x3 = 4
Use of M-File
Click to create
a new M-File

• Extension “.m”
• A text file containing script or function or program to run
Use of M-File Save file as Denem430.m

If you include “;” at the


end of each statement,
result will not be shown
immediately
Plots in MATLAB
 MATLAB provides a variety of techniques to
display data graphically.
 Interactive tools enable you to manipulate
graphs to achieve results that reveal the most
information about your data.
 You can also edit and print graphs for
presentations, or export graphs to standard
graphics formats for presentation in Web
browsers or other media.
Basic Plotting Functions
 The plot function has different forms, depending
on the input arguments. .
 If you specify two vectors as arguments, plot(x,y)
produces a graph of y versus x.
 You can also label the axes and add a title, using
the ‘xlabel’,‘ylabel’, and ‘title’ functions.
Example: xlabel('x = 0:2\pi')
ylabel('Sine of x')
title('Plot of the SineFunction','FontSize',12)
 Plotting Multiple Data Sets in One Graph
 Multiple x-y pair arguments create multiple graphs with a
single call to plot.
For example:
t = -pi : .1 : pi;
x = sin(t);
y = cos(t);
plot(t,x,'color','r'); hold on;
plot(t,y,'color','b');
hold off
xlabel(‘x axis’)
ylabel(‘y axis’)
legend('sin(x)','cos(x)')
 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')

For example: plot(x,y,'r:+')


plots a red-dotted line and places plus sign markers
at each data point.
 Figure Windows
You can add your own title to a figure window's
title bar by setting the Name property to the
desired title and you can turn off the figure
number by setting the NumberTitle property to
'off' as follows:
figure('Name','Simulation Plot Window','NumberTitle','off')
Basic Task: Plot the function sin(x)
between 0≤x≤4π
 Create an x-array of 100 samples between 0
and 4π.
>>x=linspace(0,4*pi,100);

 Calculate sin(.) of the x-array


1

0.8

>>y=sin(x); 0.6

0.4

0.2

 Plot the y-array 0

-0.2

-0.4

-0.6

>>plot(x,y) -0.8

-1
0 10 20 30 40 50 60 70 80 90 100
Plot the function e-x/3sin(x) between
0≤x≤4π
 Create an x-array of 100 samples between 0
and 4π.
>>x=linspace(0,4*pi,100);

 Calculate sin(.) of the x-array


>>y=sin(x);

 Calculate e-x/3 of the x-array


>>y1=exp(-x/3);

 Multiply the arrays y and y1


>>y2=y*y1;
Plot the function e-x/3sin(x) between
0≤x≤4π
 Multiply the arrays y and y1 correctly
>>y2=y.*y1;

 Plot the y2-array


0.7

>>plot(x,y2) 0.6

0.5

0.4

0.3

0.2

0.1

-0.1

-0.2

-0.3
0 10 20 30 40 50 60 70 80 90 100
Display Facilities
0.7

 plot(.) 0.6

0.5

0.4

Example: 0.3

>>x=linspace(0,4*pi,100);
0.2

0.1

>>y=sin(x); 0

>>plot(x,y) -0.1

-0.2

-0.3

stem(.)
0 10 20 30 40 50 60 70 80 90 100


0.7

0.6

0.5

0.4

Example: 0.3

>>stem(x,y) 0.2

0.1

-0.1

-0.2

-0.3
0 10 20 30 40 50 60 70 80 90 100
Display Facilities

 title(.)
>>title(‘This is the sinus function’)
This is the sinus function
1

0.8

 xlabel(.) 0.6

0.4

>>xlabel(‘x (secs)’) 0.2

sin(x)
0

-0.2
 ylabel(.) -0.4

-0.6

-0.8
>>ylabel(‘sin(x)’) -1
0 10 20 30 40 50 60 70 80 90 100
x (secs)
 Displaying Multiple Plots in One Figure
subplot(m,n,p)
This splits the figure window into an m-by-n matrix of
small subplots and selects the pth subplot for the current
plot
m = Number of grid rows
1 (default) | positive integer
n = Number of grid columns
1 (default) | positive integer
p = Grid position for new axes
(positive integer)
Subplot

x = linspace(0,10);
y1 = sin(x);
y2 = sin(5*x);

figure
subplot(2,1,1);
plot(x,y1)

subplot(2,1,2);
plot(x,y2)
Flow Control

 if
 for
 while
 break
 ….
Control Structures
Some Dummy Examples
 If Statement Syntax
if ((a>3) & (b==5))
Some Matlab Commands;
if (Condition_1) end
Matlab Commands
if (a<3)
elseif (Condition_2) Some Matlab Commands;
Matlab Commands elseif (b~=5)
Some Matlab Commands;
elseif (Condition_3) end
Matlab Commands
if (a<3)
else Some Matlab Commands;
Matlab Commands else
end Some Matlab Commands;
end
“if ” Example
If size(A) and size(B) are the same, concanate the arrays;
otherwise, display a warning and return an empty array.
A = ones(2,3); B = rand(3,4,5);
if isequal(size(A),size(B))
C = [A; B];
else disp('A and B are not the same size.')
C= []
end
Control Structures
Some Dummy Examples
 For loop syntax for i=1:100
Some Matlab Commands;
end

for i=Index_Array for j=1:3:200


Some Matlab Commands;
Matlab Commands end

end for m=13:-0.2:-21


Some Matlab Commands;
end

for k=[0.1 0.3 -13 12 7 -9.3]


Some Matlab Commands;
end
“for loop”

Display first 10 digits using for loop

for v = [0:1:10]
disp(v)
end
Control Structures

 While Loop Syntax

Dummy Example
while (condition)
Matlab Commands while ((a>3) & (b==5))
Some Matlab Commands;
end end
H/Ws

 By using loops in matrix, Assign 2 on main


diagonals and 0 everywhere else
“while loop”

 Use while loop to calculate the factorial of 10


“break statement”

If user input is a negative number, terminate the


loop.
Functions in MATLAB

 MATLAB has many built in functions such as,


Example

 Mean of Numbers from 1 to 100


Writing User Defined Functions

 Functions are m-files which can be executed by


specifying some inputs and supply some desired outputs.
 The code telling the Matlab that an m-file is actually a
function is
function out1=functionname(in1)
function out1=functionname(in1,in2,in3)
function [out1,out2]=functionname(in1,in2)

 You should write this command at the beginning of the m-


file and you should save the m-file with a file name same
as the function name
Writing User Defined Functions
 Examples
 Write a function : out=squarer (A, ind)

 Which takes the square of the input matrix if the input


indicator is equal to 1
 And takes the element by element square of the input
matrix if the input indicator is equal to 2

Same Name
Writing User Defined Functions
 Another function which takes an input array and returns the sum and product
of its elements as outputs

 The function sumprod(.) can be called from command window or an m-file as


Notes:
 “%” is the neglect sign for Matlab (equaivalent
of “//” in C). Anything after it on the same line
is neglected by Matlab compiler.
 Sometimes slowing down the execution is
done deliberately for observation purposes.
You can use the command “pause” for this
purpose
pause %wait until any key
pause(3) %wait 3 seconds
MATLAB Help

 Ways to get help in


MATLAB
 help function name
 Provides basic
text output
 Type helpwin on
command line
 Look under the help menu
on the desktop
MATLAB Help
 Product help window
 Help>product help
Resources

 Books
 Two that seem to be good:
 The Art of Readable Code (Simple and Practical
Techniques for Writing Better Code) by Dustin Boswel
and Trevor Foucher.
 Essential MATLAB for Engineers and Scientists (Fourth
Edition) by Brian Hahn and Dan Valentine. 2010,
Academic Press, 480 pp.
 Online tutorials and examples are
everywhere
LETS JUST END UP HERE!

If you repay good with evil, evil will


never leave your house. (PROV 17:13)

You might also like