Lecture1 MATLAB Introduction
Lecture1 MATLAB Introduction
6/7/2023
Page 1 of 101
Overview (1)
6/7/2023
Page 2 of 101
Overview (2)
6/7/2023
Page 3 of 101
Installing MATLAB
• Then you can download, install and sign in with your official email ID.
https://www.mathworks.com/downloads/web_downloads/
(Search in google with “download matlab” and you will easily get these links)
6/7/2023
Page 4 of 101
Starting MATLAB
6/7/2023
Page 5 of 101
Matlab Desktop
>> ans/2
ans =
2
6/7/2023
Page 7 of 101
M ATLAB as a Calculator (1)
>> b = 6
b =
6
>> c =
b/a c =
1.2000
6/7/2023
Page 8 of 101
Built-in Variables
>> p i
ans =
3.141
6
>>
sin(ans/4)
ans =
0.7071
6/7/2023
Page 9 of 101
Built-in Functions
6/7/2023
Page 10 of 101
Ways to Get Help
• In M ATLAB version 6 and later the doc function opens the on-line version of the
manual. This is very helpful for more complex commands.
6/7/2023
Page 11 of 101
Online Help (1)
Syntax:
help functionName
Example:
>> help log
produces→
The help function provides a compact summary of how to use a command. Use
the doc function to get more in-depth information.
6/7/2023
Page 12 of 101
Online Help (2)
6/7/2023
Page 13 of 101
Looking for Functions
Syntax:
lookfor string
produces:
6/7/2023
Page 14 of 101
Strategies for Interactive Computing
6/7/2023
Page 15 of 101
Suppress Output with Semicolon (1)
z =
3.5341
6/7/2023
Page 16 of 101
Suppress Output with Semicolon (2)
Type variable name and omit the semicolon to print the value of a variable
(that is already defined)
>> x = 5 ;
>> y = s q r t ( 5 9 ) ;
>> z = l o g ( y ) + x^0.25
z =
3.5341
>> y
y =
7.6811 ( = l o g ( s q r t ( 5 9 ) ) + 5^0.25 )
6/7/2023
Page 17 of 101
Multiple Statements per Line
c =
74.2099
6/7/2023
Page 18 of 101
M ATLAB Variables Names
Legal variable names:
• Begin with one of a–z or A–Z
• Have remaining characters chosen from a–z, A–Z, 0–9, or
• Have a maximum length of 31 characters
• Should not be the name of a built-in variable, built-in function, or
user-defined function
6/7/2023
Page 19 of 101
Built-in M ATLAB Variables (1)
Name Meaning
ans value of an expression when that expression is not assigned to
a variable
eps floating point precision
pi π, (3.141492 . . . )
realmax largest positive floating point number
realmin smallest positive floating point number
Inf ∞, a number larger than realmax,
the result of evaluating 1/0.
6/7/2023
Page 20 of 101
Built-in M ATLAB Variables (2)
6/7/2023
Page 21 of 101
Matrices and Vectors
Consequences:
• Rules of linear algebra apply to addition, subtraction and multiplication.
• Elements in the vectors and matrices are addressed with Fortran-like
subscript notation, e.g.,, x (2 ), A(4,5). Usually, this notation is clear
from context, but it can be confused with a function call,
6/7/2023
Page 22 of 101
Creating M ATLAB Variables
6/7/2023
Page 23 of 101
Element-by-Element Creation of Matrices and Vectors (1)
A matrix, a column vector, As M ATLAB variables:
and a row vector: >> A = [ 3 2 ; 3 1 ; 1 4 ]
A =
3 2 3 2
A= 3 1 3 1
1 4
1 4
>> x = [ 5 ; 7 ; 9 ; 2 ]
x =
5 5
7 7
x=
9 9
2 2
>> v = [ 9 -3 4 1 ]
v =
v= 9 −3 4 1 9 -3 4 1
6/7/2023
Page 24 of 101
Element-by-Element Creation of Matrices and Vectors (2)
For manual entry, the elements in a vector are enclosed in square brackets. When
creating a row vector, separate elements with a space.
>> v = [ 7 3 9]
v =
7 3 9
>> w = [ 2 ; 6 ; 1]
w=
2
6
1
6/7/2023
Page 25 of 101
Element-by-Element Creation of Matrices and Vectors (3)
6/7/2023
Page 26 of 101
Transpose Operator (1)
>> v = [ 2 4 1 7 ]
v =
2 4 1 7
>> w = v ’
w=
2
4
1
7
6/7/2023
Page 27 of 101
Transpose Operator (2)
>> A = [ 1 2 3 ; 4 5 6 ; 7 8 9 ]
A =
1 2 3
4 5 6
7 8 9
>> B = A’
B =
1 4 7
2 5 8
3 6 9
6/7/2023
Page 28 of 101
Overwriting Variables
>> y = [ 1 2 3 4 ]
y =
1 2 3 4
>> y = y ’
y =
1
2
3
4
6/7/2023
Page 29 of 101
Using Functions to Create Matrices and Vectors
l i n s p a c e and logspace
Note that ones and zeros can also be used to create vectors.
6/7/2023
Page 30 of 101
Creating vectors with l i n s p a c e (1)
Examples:
>> u = l i n s p a c e ( 0 . 0 , 0 . 2 5 , 5 )
u =
0 0.0625 0.1250 0.1875 0.2500
>> u = l i n s p a c e ( 0 . 0 , 0 . 2 5 ) ;
6/7/2023
Page 31 of 101
Creating vectors with l i n s p a c e (2)
6/7/2023
Page 32 of 101
Example: A Table of Trig Functions
>> x = l i n s p a c e ( 0 , 2 * p i , 6 ) ’ ; (note transpose)
>> y = s i n ( x ) ;
>> z = c o s ( x ) ;
>> [ x y z ]
ans =
0 0 1.0000
1.2566 0.9511 0.3090
2.5133 0.5878 -0.8090
3.7699 -0.5878 -0.8090
5.0265 -0.9511 0.3090
6.2832 0 1.0000
6/7/2023
Page 33 of 101
Creating vectors with logspace
x = logspace(startValue,endValue)
x = logspace(startValue,endValue,nelements)
6/7/2023
Page 34 of 101
Functions to Create Matrices (1)
6/7/2023
Page 35 of 101
Functions to Create Matrices (2)
Use ones and zeros to set intial values of a matrix or vector.
Syntax:
A = ones(nrows,ncols)
A = zeros(nrows,ncols)
Examples:
>> D = ones(3,3)
D =
1 1 1
1 1 1
1 1 1
>> E = ones(2,4)
E =
1 1 1 1
1 1 1 1
6/7/2023
Page 36 of 101
Functions to Create Matrices (3)
ones and zeros are also used to create vectors. To do so, set either
nrows or ncols to 1.
>> s = o n e s ( 1 ,4 )
s =
1 1 1 1
>> t = z e r o s ( 3 , 1 )
t =
0
0
0
6/7/2023
Page 37 of 101
Functions to Create Matrices (4)
The eye function creates identity matrices of a specified size. It can also
create non-square matrices with ones on the main diagonal.
Syntax:
A = eye(n)
A = eye(nrows,ncols)
Examples:
>> C = eye(5)
C =
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
6/7/2023
Page 38 of 101
Functions to Create Matrices (5)
The optional second input argument to eye allows non-square matrices to
be created.
>> D = e ye (3,5)
D =
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
where D i , j = 1 whenever i = j.
6/7/2023
Page 39 of 101
Functions to Create Matrices (6)
The diag function can either create a matrix with specified diagonal
elements, or extract the diagonal elements from a matrix
Syntax:
A = diag(v)
v = diag(A)
6/7/2023
Page 40 of 101
Functions to Create Matrices (7)
Example: Use diag to extract the diagonal of a matrix
>> B = [ 1 : 4 ; 5 : 8 ; 9 : 1 2 ]
B =
1 2 3 4
5 6 7 8
9 10 11 12
>> w = d i a g ( B )
w=
1
6
11
6/7/2023
Page 41 of 101
Functions to Create Matrices (8)
>> B = [ 4 2 2 ; 3 6 9 ; 1 1 7 ] ;
>> v = d i a g ( B ) Extract the diagonal of a matrix
v =
4
6
7
6/7/2023
Page 42 of 101
Subscript Notation (1)
If A is a matrix, A ( i , j ) selects the element in the ith row and jth column.
Subscript notation can be used on the right-hand side of an expression to
refer to a matrix element.
>> A = [ 1 2 3 ; 4 5 6 ; 7 8 9 ] ;
>> b = A ( 3 , 2 )
b =
8
>> c = A ( 1 , 1 )
c =
1
6/7/2023
Page 43 of 101
Subscript Notation (1)
6/7/2023
Page 44 of 101
Subscript Notation (1)
>> A ( 4 , 4 ) = 11
A =
1 2 3 0
4 5 6 0
7 8 9 0
0 0 0 11
6/7/2023
Page 45 of 101
Colon Notation (1)
Colon notation is very powerful and very important in the effective use of
M ATLAB . The colon is used as both an operator and as a wildcard.
6/7/2023
Page 46 of 101
Colon Notation (2)
Syntax:
startValue : endValue
startValue : increment : endValue
6/7/2023
Page 47 of 101
Colon Notation (3)
>> t = 0 : 0 . 1 : 0 . 4
t =
0 0.1000 0.2000 0.3000 0.4000
6/7/2023
Page 48 of 101
Colon Notation (4)
>> v = 1 : 5 ’
v =
1 2 3 4 5
6/7/2023
Page 49 of 101
Colon Notation (5)
>> A ( 2 , : )
ans =
4 5 6
6/7/2023
Page 50 of 101
Colon Notation (6)
>> A ( 1 : 2 , 2 : 3 )
ans =
ans =
2 3
5 6
6/7/2023
Page 51 of 101
Colon Notation (7)
6/7/2023
Page 52 of 101
Colon Notation (8)
Finally, colon notation is used to convert any vector or matrix to a column vector.
Example:
>> x = 1 : 4 ;
>> y = x ( : )
y =
1
2
3
4
Note: The rand function generates random elements between zero and one.
Repeating the preceding statements will, in all likelihood, produce different
numerical values for the elements of v.
6/7/2023
Page 54 of 101
Additional Types of Variables
6/7/2023
Page 55 of 101
Complex Numbers
M ATLAB automatically performs complex arithmetic
>> s q r t ( - 4 )
ans =
0 + 2.0000i
>> y = 1 - 2 * i
y =
1.0000 - 2.0000i
>> z = x*y
z =
5
6/7/2023
Page 56 of 101
Unit Imaginary Numbers (1)
The i and j variables are often used for array subscripting. Set i (or j ) to
an integer value that is also a valid array subscript.
>> A = [1 2 ; 3 4 ] ;
>> i = 2 ;
>> A ( i , i ) = 1
A =
1 2
3 1
>> x = A ( 2 , j )
??? S u b s c r i p t i n d i c e s must e i t h e r be r e a l p o s i t i v e i n t e g e r s or l o g i c a l s .
6/7/2023
Page 58 of 101
Euler Notation (1)
imaginary
z = ζe iθ
x = Re(z) = |z| cos(θ) = ζ cos(θ) iy z = ei
y = iIm(z) = i|z| sin(θ) = iζ sin(θ)
x real
6/7/2023
Page 59 of 101
Functions for Complex Arithmetic (1)
Function Operation
abs Compute the magnitude of a number
a b s ( z ) is equivalent to s q r t ( r e a l ( z ) ^ 2 + imag(z)^2 )
angle Angle of complex number in Euler notation
exp If x is real, exp(x) = e x
If z is complex, exp(z) = eRe(z)(cos(Im(z) + i sin(Im(z))
conj Complex conjugate of a number
imag Extract the imaginary part of a complex number
real Extract the real part of a complex number
Examples:
>> z e t a = 5 ; theta = p i / 3 ; >> x = r e a l ( z )
>> z = z e t a * e x p ( i * t h e t a ) x =
z = 2.5000
2.5000 + 4.3301i
>> y = imag(z)
>> a b s ( z ) y =
ans = 4.3301
5
>> a n g l e (z)*1 80 /pi
>> s q r t ( z * c o n j ( z ) ) ans =
ans = 60.0000
5
>> name(9:13)
ans =
trane
Function Operation
char Converts an integer to the character using ASCII codes, or
combines characters into a character matrix
findstr Finds one string in another string
length Returns the number of characters in a string
num2str Converts a number to string
str2num Converts a string to a number
strcmp Compares two strings
strmatch Identifies rows of a character array that begin with a string
strncmp Compares the first n elements of two strings
sprintf Converts strings and numeric values to a string
Use strcmp to test whether two strings are equal, i.e., if they contain the
same sequence of characters.
>> msg1 = [ ’ T h e r e are ’ , n u m 2 s t r ( 1 0 0 / 2 . 5 4 ) , ’ inches i n a m e t e r ’ ] ;
>> msg2 = s p r i n t f ( ’ T h e r e are %5.2f c u b i c inches i n a l i t e r ’ , 1 0 0 0 / 2 . 5 4 ^ 3 ) ;
>> strcmp(msg1,msg2)
ans =
0
>> msg1(19:20)
ans =
in
Page 67 of 101
6/7/2023
Polynomials
M ATLAB polynomials are stored as vectors of coefficients. The polynomial
coefficients are stored in decreasing powers of x
P n (x) = c 1 x n + c 2 x n−1 + . . . + c n x + c n + 1
>> u-v
ans =
9 7 5
𝜎 = 𝑢. 𝑣 = 𝑢𝑣 𝑇 ↔ 𝜎 = 𝑢𝑖 𝑣𝑖
A = u T v ⇐⇒ a i , j = u i v j
Page 72 of 101
6/7/2023
Inner and Outer Products in M ATLAB
Page 73 of 101
6/7/2023
Vectorization
2Recent versions of M ATLAB have improved the efficiency for some non-vectorized code.
Most built-in function support vectorized operations. If the input is a scalar the
result is a scalar. If the input is a vector or matrix, the output is a vector or
matrix with the same number of rows and columns as the input.
Example:
>> x = 0 : p i / 4 : p i (define a row vector)
x =
0 0.7854 1.5708 2.3562 3.1416
More examples
>> A = p i * [ 1 2 ; 3 4 ] >> B = A/2
A = B =
3.1416 6.2832 1.5708 3.1416
9.4248 12.5664 4.7124 6.2832
>> S = s i n ( A ) >> T = s i n ( B )
S = T =
0 0 1 0
0 0 -1 0
Page 76 of 101
6/7/2023
Array Operators
Symbol Operation
.* element-by-element multiplication
.^ element-by-element exponentiation
Array operators are a very important tool for writing vectorized code.
>> x = u . / v
x =
0.2500 0.4000 0.5000
>> z = s i n ( p i * u / 2 ) . / c o s ( p i * v / 2 )
Warning: D i v i d e by z e r o .
z =
1 NaN 1
Page 79 of 101
6/7/2023
Using Array Operators (2)
>> A*B
??? E r r o r using ==> *
Inner matrix dimensions must agree
>> A = [ 1 2 3 4 ; 5 6 7 8 ] ;
>> B = [ 8 7 6 5 ; 4 3 2 1 ] ;
>> A*B’
ans =
60 20
164 60
>> a = 5; b = 2; c = 1;
>> d ( 1 ) = sqrt(b^2 - 4*a*c);
>> d(2) = -d ( 1 ) ;
>> who
Your v a r i a b l e s a r e :
a b c d
Page 83 of 101
6/7/2023
The M ATLAB Workspace (3)
The whos command lists the name, size, memory allocation, and the class
of each variables defined in the workspace.
>> whos
Page 85 of 101
6/7/2023
Working with External Data Files
M ATLAB will only use those functions and data files that are in its path.
To add N:\IMAUSER\ME352\PS2 to the path, type
>> p = path;
>> path(p,’N:\IMAUSER\ME352\PS2’);
M ATLAB version 5 and later has an interactive path editor that makes it
easy to adjust the path.
The path specification string depends on the operating system. On a
Unix/Linux computer a path setting operation might look like:
>> p = path;
>> path(p,’~/matlab/ME352/ps2’);
Page 88 of 101
6/7/2023
Plotting
Note: x and y must have the same shape, x1 and y1 must have the
same shape, x2 and y2 must have the same shape, etc.
Page 90 of 101
6/7/2023
Plotting (x, y) Data (2)
1
Example: A simple line plot 0.8
>> x = l i n s p a c e ( 0 , 2 * p i ) ; 0.6
>> y = s i n ( x ) ; 0.4
>> p l o t ( x , y ) ; 0.2
−0.2
−0.4
−0.6
−0.8
−1
0 1 2 3 4 5 6 7
Page 91 of 101
6/7/2023
Line and Symbol Types (1)
The curves for a data set are drawn from combinations of the color,
symbol, and line types in the following table.
Color Symbols Line
y yellow . point ^ triangle (up) - solid
m magenta o circle < triangle (left) : dotted
c cyan x x-mark > triangle (right) -. dashdot
r red + plus p pentagram -- dashed
g green * star h hexagram
b blue s square
w white d diamond
k black v triangle
(down)
Examples:
Put yellow circles at the data points:
plot(x,y,’yo’)
Put black diamonds at each data point and connect the diamonds with black das
p l o t ( x , y , ’ k d - - ’)
Page 93 of 101
6/7/2023
Alternative Axis Scaling (1)
Note: As expected, use of logarithmic axis scaling for data sets with
negative or zero values results in a error. M ATLAB will complain
and then plot only the positive (nonzero) data.
10
Example:
8
>> x = l i n s p a c e ( 0 , 3 ) ;
6
>> y = 1 0 * e x p ( -2*x);
>> p l o t ( x , y ) ; 4
2
0
0 1 2 3
1
10
>> s e m i l o g y ( x , y ) ;
0
10
-1
10
-2
10
0 1 2 3
Repeat the values of nrows and ncols for all plots in a single figure
window. Increment thisPlot for each plot
Page 96 of 101
6/7/2023
Multiple plots per figure window (1)
Example:
>> x = l i n s p a c e ( 0 , 2 * p i ) ;
>> s u b p l o t ( 2 , 2 , 1 ) ;
>> p l o t ( x , s i n ( x ) ) ; axis([0 2*pi - 1 . 5 1 . 5 ] ) ; title(’sin(x)’);
>> s u b p l o t ( 2 , 2 , 2 ) ;
>> p l o t ( x , s i n ( 2 * x ) ) ; axis([0 2*pi - 1 . 5 1 . 5 ] ) ; title(’sin(2x)’);
>> s u b p l o t ( 2 , 2 , 3 ) ;
>> p l o t ( x , s i n ( 3 * x ) ) ; axis([0 2*pi - 1 . 5 1 . 5 ] ) ; title(’sin(3x)’);
>> s u b p l o t ( 2 , 2 , 4 ) ;
>> p l o t ( x , s i n ( 4 * x ) ) ; axis([0 2*pi - 1 . 5 1 . 5 ] ) ; title(’sin(4x)’);
Page 97 of 101
6/7/2023
Multiple plots per figure window (2)
sin(x) sin(2x)
1.5 1.5
1 1
0.5 0.5
0 0
-0.5 -0.5
-1 -1
-1.5 -1.5
0 2 4 6 0 2 4 6
sin(3x) sin(4x)
1.5 1.5
1 1
0.5 0.5
0 0
-0.5 -0.5
-1 -1
-1.5 -1.5
0 2 4 6 0 2 4 6
Page 99 of 101
6/7/2023
Plot Annotation Example (1)
>> p l o t ( m , t ( : , 1 ) , ’ r o ’ , m , T ( : , 2 ) , ’ k + ’ , m , T ( : , 3 ) , ’ b - ’);
>> xlabel(’Month’);
>> ylabel(’Temperature ( { } ^ \ c i r c F ) ’ ) ;
>> t i t l e ( ’ M o n t h l y average temperature a t P D X ’ ) ;
>> a x i s ( [ 1 12 20 1 0 0 ] ) ;
>> legend(’High’,’Low’,’Average’,2);
80
Temperature (degrees F)
70
60
50
40
30
20
2 4 6 8 10 12
Month
Course Link:
https://matlabacademy.mathworks.com/details/matlab-onramp/gettingstarted