Sunteți pe pagina 1din 93

Introduction to Matlab

Outline:
What is Matlab?
• Matlab Screen
• Variables, array, matrix, indexing
• Operators (Arithmetic, relational, logical )
• 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 stands for MATrix LABoratory. Cleve
Moler is a mathematician and computer
programmer. In the mid to late 1970s, he
invented MATLAB, a numerical computing
package, to give his students at the University of
New Mexico easy access to Fortran libraries for
numerical computing without writing Fortran.
What are we interested in?
• Matlab is too broad for our purposes in this
course.
• The features we are going to require is
Matlab
Series of
Matlab
commands
Command
m-files mat-files
Line

functions Command execution Data


Input like DOS command storage/
Output window loading
capability
Matlab Screen
• 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
Main Matlab Window
Command Window
type commands

Workspace

Command History
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 x1 = [1 2 5 1]

x1 =
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

• transpose y = x1’ y = 1
2
5
1
%Matrix computations and operations
>> %creating vectors and matrices
>> %create a row vector, we can form a row vector.

>> a=[1 3 6 8];

>> a

a=

1 3 6 8
>> %create a column vector,

>> b=[1;4;6;10];
>> b

b=

1
4
6
10
Create the matrix x of 3 rows and 4 columns

x=[12 23 21 3; 2 34 5 7; 31 32 33 34];
>> x

x=

12 23 21 3
2 34 5 7
31 32 33 34
%elements of a Matrix

>> z=x(2,3)
x=
z=
5 12 23 21 3
>> x1=x(1,:)
2 34 5 7
x1 = 31 32 33 34

12 23 21 3
>> x2=x(:,2)
x2 =
23 x=
34
32 12 23 21 3
2 34 5 7
>> s=size(x) 31 32 33 34
s=
3 4
Long Array, Matrix
• t =1:1:10

t = 1 2 3 4 5 6 7 8 9 10

• t =1:10
t = 1 2 3 4 5 6 7 8 9 10

• k =2:-0.5:-1

k = 2 1.5 1 0.5 0 -0.5 -1

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

B =
1 2 3 4
5 6 7 8
Remove the n th
Row or column of the given matrix
X(n, : ) = [ ]
x(2, : ) = [ ]

X( : ,n ) = [ ]
x( : , 2 ) = [ ] x=
12 23 21 3
2 34 5 7
31 32 33 34
Add a column of 4,s to the end of matrix.
x( : , 4) = 4 x=
12 23 21 4
2 34 5 4
31 32 33 4
Remove the 2 nd Row
x= Remove the 2 nd Column
12 23 21 3 x( : , 2 ) = [ ]
2 34 5 7
31 32 33 34
x=
12 21 3
x(2, : ) = [ ] 2 5 7
x= 31 33 34
12 23 21 3
31 32 33 34
Add 4 th Column
Add 2 nd Row

x(2, : ) = [12 23 21 3 ] x( : , 4 ) = [ 23;34;32]

x= x =12 23 21 23
12 23 21 3 2 34 5 34
12 23 21 3 31 32 33 32
31 32 33 34
We can extend the colon notation to specify a
sequence
Create a vector v which starts at 1, with increment of 2
and stops at 10:

v=1:2:10
v=
1 3 5 7 9

>> v=1:10

v=

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

x = ones(1,3)
• ones(M,N) MxN matrix of ones x = 1 1 1

x = rand(1,3)
• rand(M,N) MxN matrix of x =
uniformly 0.9501 0.2311 0.6068
distributed random
numbers on (0,1)
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]

1 2 4 5

B = [x ; y]

1 2
4 5

C = [x y ;z]
Error:
??? Error using ==> vertcat CAT arguments dimensions are not consistent.
Arithmetic Operators
+ Addition
- Subtraction
* Multiplication
/ Right Division
\ Left Division
^ Power/ Exponentiation
‘ Complex conjugate transpose
Examples:

>> a=7;
>> b=8;
>> a+b

ans =
15

>> (a+b)/2

ans =

7.5000
>> 5^3/2

ans =

62.5000

>> 27^(1/3)^0.2

ans =

1.2457

>> 27^(1/3)+32^0.2
ans =
5
ARITHMETIC OPRATIONS :

Compute the following :


Arithmetic operations; Compute the following quantities:
1. Solution:

LHS=2^5/(2^5-1)

LHS =

1.0323

>> RHS=(1-1/2^5)^-1

RHS =

1.0323
2. Solution

>>3*((5^(0.5)-1)/(5^(0.5)+1)^2)-1

ans =

-0.6459

3. Solution
area = pi*(pi^(1/3) - 1)^2
𝐓𝐑𝐈𝐆𝐎𝐍𝐎𝐌𝐄𝐓𝐑𝐘
1(a). Solution

>> sin(pi/6)
ans =
0.5000

1(b). Solution
>> cos(pi)

ans =
-1
1(c). Solution

tan(pi/2)
2. Solution

>> (sin(pi/6))^2+(cos(pi/6))^2

ans =
1

3. Solution

>> x=32*pi;
>> y=(cosh(x))^2-(sinh(x))^2
y=
0
EXPONENTIAL AND LOGARITHMS
6. Solution 7. Solution

>> log10(exp(3))
>> exp(3)
ans =
ans =
1.3029
20.0855
>> x=log(17)/log(3)
>> log(exp(3))
x=
ans =
2.5789
3
𝐂𝐎𝐌𝐏𝐋𝐄𝐗 𝐍𝐔𝐌𝐁𝐄𝐑𝐒
>> %complex numbers:

MATLAB recognizes the letter i and j as the


imaginary numbers √-1

>> (1+3i)/(1-3i)
ans =
-0.8000 + 0.6000i

>> exp(i*pi/4)
ans =
0.7071 + 0.7071i
Euler’s formula e ix = cosx + i sinx (x = pi/2)

>> cos(pi/2) + i*sin(pi/2)

ans =

0.0000 + 1.0000i

>> cos(pi/2) - i*sin(pi/2)

ans =

0.0000 - 1.0000i
exp(i*pi/2)

ans =

0.0000 + 1.0000i
Matrix

>> x=[1 2 3 4]

x=
1 2 3 4

>> y=x.'

y=
1
2
3
4
>> A=[1,2,3; 4,-5,6; 5,-6,7]

A=

1 2 3
4 -5 6
5 -6 7

>> b=A'

b=

1 4 5
2 -5 -6
3 6 7
>> inv(A)

ans =

0.1250 -4.0000 3.3750


0.2500 -1.0000 0.7500
0.1250 2.0000 -1.6250

>> A'

ans =

1 4 5
2 -5 -6
3 6 7
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
Useful Commands

• The two commands used most by Matlab


users are
>>help functionname

>>lookfor keyword
Example 1
Change the format to long by typing
format long
View the result for the value of pi by typing
pi
ans = 3.14159265358979

View the current format by typing


get(0,'format')
ans = long

Set the format to short e by typing


format short e
or use the function form of the syntax
format('short','e')
Example 2

When the format is set to short, both pi and


single(pi) display as 5-digit values:

>>format short pi
ans = 3.1416

>>single(pi)
ans = 3.1416
Now set format to long, and pi displays a 15-digit
value while single(pi) display an 8-digit value:

>>format long pi
ans = 3.14159265358979

>>single(pi)
ans = 3.1415927
Example 4

This example illustrates the short eng and long eng


formats.

The value assigned to variable A increases by a


multiple of 10 each time through the for loop.

A = 5.123456789;
for k=1:10
A = A * 10;
disp(A)
end
The values displayed for A are shown here. The power
of 10 is always a multiple of 3. The value itself is
expressed in 5 or more digits for the short eng format,
and in exactly 15 digits for long eng:

format short eng format long eng


5.1235e+000 5.12345678900000e+000
51.2346e+000 51.2345678900000e+000
512.3457e+000 512.345678900000e+000
5.1235e+003 5.12345678900000e+003
51.2346e+003 51.2345678900000e+003
512.3457e+003 512.345678900000e+003
5.1235e+006 5.12345678900000e+006
51.2346e+006 51.2345678900000e+006
512.3457e+006 512.345678900000e+006
5.1235e+009 5.12345678900000e+009
Equation of straight line: y= mx + c, where m and c are
constants. Compute the y- coordintes of line with slope
m= 0.5 and the intercept c= -2 at the following x-
coordinates:
x= 0, 1.5, 3, 4,5, 7, 9, and 10.
Solution:

>> x= [0 1.5 3 4 5 7 9 10];


>> m=0.5;
>> c=-2;
>> y= m*x+c
y=

-2.0000 -1.2500 -0.5000 0 0.5000 1.5000


2.5000 3.0000
Operators (Element by Element)

.*element-by-element multiplication
./ element-by-element division
.^element-by-element power
Matrices Operations

Given A and B:

Addition Subtraction Product Transpose


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.
Vectors and Matrices

• Arithmetic operations – Matrices


Performing operations to every entry in a matrix
Power
>>> A=[1 2 3;4 5 6;7 8 9]
A= To square every element in A, use
1 2 3 the element–wise operator .^
4 5 6
7 8 9 >>> A.^2
>>> ans =
1 4 9
16 25 36
49 64 81
>>> A^2
ans =
A^2 = A * A 30 36 42
66 81 96
102 126 150
Vectors and Matrices

• Arithmetic operations – Matrices


Performing operations between matrices
>>> A=[1 2 3;4 5 6;7 8 9] >>> B=[1 1 1;2 2 2;3 3 3]
A = B =
1 2 3 1 1 1
4 5 6 2 2 2
7 8 9 3 3 3

1 2 3  1 1 1  14 14 14 
 4 5 6  2 2 2 = 32 32 32 
A*B      
7 8 9 3 3 3 50 50 50 

 1x1 2x1 3x1  1 2 3


 4 x 2 5x 2 6 x 2  8 10 12 
A.*B  
=  
 7 x3 8x3 9x3 21 24 27 
Vectors and Matrices

• Arithmetic operations – Matrices


Performing operations between matrices

A/B ? (matrices
singular)
 1 / 1 2 / 1 3 / 1 1.0000 2.0000 3.0000
A./B  4 / 2 5 / 2 6 / 2 = 2.0000 2.5000 3.0000
   
7 / 3 8 / 3 9 / 3 2.3333 2.6667 3.0000
Vectors and Matrices

• Arithmetic operations – Matrices


Performing operations between matrices

??? Error using ==> ^


A^B At least one operand must be scalar

 11 21 31   1 2 3 
A.^B  2 2   16 36 
 4 5 62  =

25

73 83 93  343 512 729

Points on a circle:
All points coordinates x =rcosθ and y rsinθ, where r is a
constant, lies on a circle with radius r, i.e they satisfy the
equation r2 = x2 + y2. Create a column vector for θ with
the values 0, pi/4, pi/2, 3*pi/4, pi, 5*pi/4. Take r =2 and
compute the column vectors x and y and check that x
and y indeed satisfy the equation of a circle, by
computing the radius r =
Solution: Points on a circle:
theta= [0; pi/4; pi/2; 3*pi/4; pi; 5*pi/4]
theta =
0
0.7854
1.5708
2.3562
3.1416
3.9270
Script:
r=2;
x=r*cos(theta);
y=r*sin(theta);
x.^2+y.^2
r=sqrt(x.^2+y.^2)
Output: r = 2
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

>>y=sin(x);
0.8

0.6

0.4

0.2

• Plot the y-array 0

-0.2

-0.4

-0.6

>>plot(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(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

0.6

• plot(.)
0.5

0.4

0.3

Example:
0.2

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

>>y=sin(x); -0.1

>>plot(y) -0.2

>>plot(x,y) -0.3
0 10 20 30 40 50 60 70 80 90 100

0.7

• stem(.) 0.6

0.5

0.4

0.3

Example:
0.2

0.1
>>stem(y) 0

>>stem(x,y) -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)
Built in functions (commands)

Data visualisation – plotting graphs

>>> help graph2d


>>> help graph3d

e.g. plot polar loglog mesh


semilog plotyy surf
Built in functions (commands) eg1_plt.m

Data visualisation – plotting graphs


Example on plot – 2 dimensional plot

Example on plot – 2 dimensional plot


>>> x=linspace(0,(2*pi),100);
>>> y1=sin(x); Add title, labels and legend
>>> y2=cos(x);
>>> plot(x,y1,'r-') title xlabel ylabel legend

>>> hold
Current plot held
>>> plot(x,y2,'g--')
>>>
Built in functions (commands) eg1_plt.m

Data visualisation – plotting graphs


Example on plot – 2 dimensional plot
Example on plot
1
sin(x)
0.8 cos(x)

0.6

0.4

0.2
y1 and y2

-0.2

-0.4

-0.6

-0.8

-1
0 1 2 3 4 5 6 7
angular frequency (rad/s)
Built in functions (commands) eg2_srf.m

Data visualisation – plotting graphs


Example on mesh and surf – 3 dimensional plot
Supposed we want to visualize a function
Z = 10e(–0.4a) sin (2ft) for f = 2
when a and t are varied from 0.1 to 7 and 0.1 to 2, respectively

>>> [t,a] = meshgrid(0.1:.01:2, 0.1:0.5:7);


>>> f=2;
>>> Z = 10.*exp(-a.*0.4).*sin(2*pi.*t.*f);
>>> surf(Z);
>>> figure(2);
>>> mesh(Z);
Built in functions (commands) eg2_srf.m

Data visualisation – plotting graphs


Example on mesh and surf – 3 dimensional plot
Built in functions (commands) eg3_srf.m

Data visualisation – plotting graphs


Example on mesh and surf – 3 dimensional plot

>>> [x,y] = meshgrid(-3:.1:3,-3:.1:3);


>>> z = 3*(1-x).^2.*exp(-(x.^2) - (y+1).^2) ...
- 10*(x/5 - x.^3 - y.^5).*exp(-x.^2-y.^2) ...
- 1/3*exp(-(x+1).^2 - y.^2);
>>> surf(z);
Built in functions (commands) eg2_srf.m

Data visualisation – plotting graphs


Example on mesh and surf – 3 dimensional plot
Relational And Logical Operators
Relational Operators
• == Equal to
• ~= Not equal to
• < Strictly smaller
• > Strictly greater
• <= Smaller than or equal to
• >= Greater than equal to
Logical Operators
• & And operator
• | Or operator
• ~ NOT
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
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
Control Structures
• While Loop Syntax
Dummy Example

while (condition) while ((a>3) & (b==5))


Matlab Commands Some Matlab Commands;
end
end
M-files :
Script and function files
When problems become complicated and require re–
evaluation, entering command at MATLAB prompt is
not practical
Solution : use M-files

Script Function
Collections of commands User defined commands

Executed in sequence when called Normally has input & output

Saved with extension “.m”


Saved with extension “.m”
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
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
Writing User Defined Functions
•The function sumprod(.) can be called from
command window or an m-file as
Assignments

Create matrix X of 4 rows and 3 columns.


i) Add 4 to matrix X to create new matrix called Y.
ii) Can we add and subtract X and Y? Justify your
answer.
iii) Remove second row from matrix X.
iv) Add a column of 6’s to the end of matrix Y.
Solve the following expressions in MATLAB command window.
Assignments

Assume that a[1 0; 2 1] , b[ -1 2; 0 1] ,c [ 3; 2] and d = 5.


What is the result of each of the following expressions?
1. a+ b
2. a .* b
3. a * b
4. a * c
5. a + c
6. a+ d
7. a .*d
8. a* d
ans4 =
ans1 =
3
0 2
8
2 2
ans6 =
ans2 =
6 5
7 6
-1 0
0 1
ans7 =
5 0
10 5
ans3 =
ans8 =
-1 2
5 0
-2 5
10 5
Practice
Program to calculate the square,squareroot
and cuberoot of all the numbers starting
from 1 upto given number using for loop:
x= input('Enter the number: ');
squ=1;
squ_root=1;
cube_root=1;
for c = 1:x
squ(c)= c^2;
squ_root(c)= c^(1/2);
cube_root(c)= c^(1/3);
end
fprintf('Square: %d\n',squ);
fprintf('squre_root: %f\n',squ_root);
fprintf('cube root: %f\n',cube_root);
Results
Enter the number: 4
Square: 1
Square: 4
Square: 9
Square: 16

squre_root: 1.000000
squre_root: 1.414214
squre_root: 1.732051
squre_root: 2.000000

cube root: 1.000000


cube root: 1.259921
cube root: 1.442250
cube root: 1.587401
% Program to calculate the
%square,square root and cube root
%using while loop:

Script:

x= input('Enter the number: ');


squ=1;
squ_root=1;
cube_root=1;
c=1;
while (c<=x)
squ(c)= c^2;
squ_root(c)= c^(1/2);
cube_root(c)= c^(1/3);
c=c+1;
end
fprintf('Square: %d\n',squ);
fprintf('squre_root: %f\n',squ_root);
fprintf('cube root: %f\n',cube_root);
Results
Enter the number: 4
Square: 1
Square: 4
Square: 9
Square: 16

squre_root: 1.000000
squre_root: 1.414214
squre_root: 1.732051
squre_root: 2.000000

cube root: 1.000000


cube root: 1.259921
cube root: 1.442250
cube root: 1.587401
% Program to calculate the square,square root
and cube root by vectorization method:
x= input('Enter the number: ');
squ=1;
squ_root=1;
cube_root=1;
c=1:x;
squ(c)= c.^2;
squ_root(c)= c.^(1/2);
cube_root(c)= c.^(1/3);
fprintf('Square: %d\n',squ);
fprintf('squre_root: %f\n',squ_root);
fprintf('cube root: %f\n',cube_root);
qu2_vec
Enter the number: 4
Square: 1
Square: 4
Square: 9
Square: 16
squre_root: 1.000000
squre_root: 1.414214
squre_root: 1.732051
squre_root: 2.000000
cube root: 1.000000
cube root: 1.259921
cube root: 1.442250
cube root: 1.587401

S-ar putea să vă placă și