You are on page 1of 62

MATLAB BASICS

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 1


B BASICS_MARCH 2023
How to install MATLAB
• Follow this YouTube link
https://youtu.be/kymKy2w_tJs

MATLAB TUTOR: Mr. PATEL


BHAVIK MAHESHKUMAR
Email: bpatel@iitg.ac.in
M: 9725200781

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 2


B BASICS_MARCH 2023
•MATLAB MATrix LABoratory

Developed by Math Works Inc

Display Window
•Command Window
•Graphics Window
•Edit Window

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 3


B BASICS_MARCH 2023
Starting and quitting MATLAB
To start click on MATLAB icon

To quit either write quit or exit


>>quit
>>exit
•Change of directory
>>Pwd % Show present directory
>>cd %for changing directory
% Also you may change to the required
directory from the command window
S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 4
B BASICS_MARCH 2023
S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 5
B BASICS_MARCH 2023
S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 6
B BASICS_MARCH 2023
S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 7
B BASICS_MARCH 2023
S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 8
B BASICS_MARCH 2023
Use of semicolon
If a semicolon (;) is typed at the end of a
command the output of the command is not
displayed
>>t=0:0.1:2*pi;
>>y = exp(t/10).*sin(t);
>>plot(t,y)
>>xlabel('Time (t) in second')
>>ylabel('Response amplitude in mm')

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 9


B BASICS_MARCH 2023
• To comment a sentence or line in command
window or M-file use %
% This program is for finding the frequency response
% of the system
To clean the command window use clc
>>clc
To get help
>> help

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 10


B BASICS_MARCH 2023
Statement and Variable
>>variable=expression
>> a=5
a=
5
>> a=5;
>>
>> b=[1 5]
b=
1 5
>> c=[4;7]

c=
4
S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 11
7 B BASICS_MARCH 2023
Matrix Manipulation
This demo examines some basic matrix manipulations in
MATLAB. We start by creating a magic square and
assigning it to the variable A
>>A = magic(3)
A=

8 1 6
3 5 7
4 9 2
Here's how to add 2 to each element of A.
S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 12
B BASICS_MARCH 2023
Note that MATLAB requires no special handling of
matrix math.
>>A+2
ans =
10 3 8
5 7 9
6 11 4

The apostrophe symbol denotes the complex conjugate


transpose of a matrix. Here's how to take the transpose
of A
S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 13
B BASICS_MARCH 2023
Transpose of A
>>A'
ans =

8 3 4
1 5 9
6 7 2

The symbol * denotes multiplication of matrices

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 14


B BASICS_MARCH 2023
Let's create a new matrix B and multiply A by B
>>B = 2*ones(3)
B=
2 2 2
2 2 2
2 2 2
>>A*B
ans =
30 30 30
30 30 30

S.K. Dwivedy
30 30 30 IITG/MECH/SKD_ME101_MATLA 15
B BASICS_MARCH 2023
We can also multiply each element of A with
its corresponding element of B by using the .*
operator.
>>A.*B 8 1 6  2 2 2
ans = A =  3 5 7  , B =  2 2 2 
 4 9 2   2 2 2 

16 2 12
6 10 14
8 18 4

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 16


B BASICS_MARCH 2023
Arithmetic Operation

Arithmetic Symbol Example


operation
Addition + 5+3=8
Subtraction - 9-2=7
Multiplication * 4*5=20
Right division / 20/5=4
Left division \ 10\2=0.2
Exponentiation ^ 2^3=8

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 17


B BASICS_MARCH 2023
Command Description Example
( 250/3)
format short Fixed point with 4 decimal digits 83.3333

format long Fixed point with14 decimal 83.33333333333333


digits
format short e Scientific 4 decimal digits 8.3333e+001
format long e Scientific 15 decimal digits 8.333333333333333e+
001
format short g Best of 5 digits fixed or floating 83.333

format long g Best of 15 digits fixed or floating 83.3333333333333

format bank Two decimal digits


83.33
format compact Eliminate empty lines
format loose Add empty lines

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 18


B BASICS_MARCH 2023
Built in functions in MATLAB
Function Description

abs(x)

sqrt(x)

round(x) Nearest integer


fix(x) Truncate towards zero
floor(x) Round towards −
ceil(x) Round towards 
sign(x) -1 if x <0,=0 at x=0 and 1 for x >0
rem(xy) Return the remainder of x/y rem(10,3)=1

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 19


B BASICS_MARCH 2023
exp(x) ex
log(x) ln(x)
log10(x) Base 10
sin(x)
cos(x)
tan(x)
asin(x) − / 2 to  / 2
acos(x) 0 to 
atan(x) − / 2 to  / 2
sinh(x)
cosh(x)
tanh(x)
asinh(h)
acosh(x)
atanh(x)
S.K. Dwivedy atan2(y,x) atan2(-0.5,0.5)=0.79 and atan2(0.5,-0.5)=2.36
IITG/MECH/SKD_ME101_MATLA 20
B BASICS_MARCH 2023
Arithmetic operation with complex numbers
>> a=2+3i;
>>b=4+6i;
>>c=3+6i;
>>c=a+b 6.0000+9.0000i
>>a*b -10.0000 +24.0000i
>>conj(a) 2.0000-3.0000i
>>a/c 0.5333 - 0.0667i
>>real(a) 2.0000
>>imag(a) 3.0000
>> abs(a) 3.6056
>> angle(a) 0.9828

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 21


B BASICS_MARCH 2023
Predefined variable in MATLAB

ans
pi
eps
inf
i
j
NaN
clock
date

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 22


B BASICS_MARCH 2023
Workspace Information

who whos
what clear
clear x y z clear all
mlock fun munlock fun
clc home
clf pwd
cd dir
ls path
edit path copyfile
S.K. Dwivedy mkdir IITG/MECH/SKD_ME101_MATLA 23
B BASICS_MARCH 2023
Plotting simple graphs

t=0:0.1:2*pi;
y = exp(t/10).*sin(t);
plot(t,y);
xlabel('Time (t) in second')
ylabel('Response amplitude in mm')
%print resp_amp.pdf -dpdf

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 24


B BASICS_MARCH 2023
Plotting simple graphs

fplot('exp(-0.1*t).*sin(t)',[0,30])
xlabel('time')
ylabel('f(x)=e^{0.1 t}sin(t)')
title('A function plotted with (fplot')
print f2.jpg -djpeg

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 25


B BASICS_MARCH 2023
Plotting simple graphs

g=inline('x^2');
ezplot(g)
title('A plot using ezplot command')
print f3.jpg -djpeg

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 26


B BASICS_MARCH 2023
Plotting simple graphs

r=inline('1+2.*sin(2*t)'); ! defult -2pi to 2pi


ezpolar(r)
title('Figure using ezpolar')
print f4.jpg -djpeg

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 27


B BASICS_MARCH 2023
Plotting simple graphs

x='t1.*cos(2.*pi*t1)';
y='t1.*sin(2*pi*t1)';
z='t1';
ezplot3(x,y,z)
title('Figure using ezplot3')
print f5.jpg -djpeg

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 28


B BASICS_MARCH 2023
Plotting simple graphs

Z=inline('cos(2*x).*cos(y).*exp(-sqrt((x.^2+y.^2)/4))');
ezcontour(Z)
print f6.jpg -djpeg

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 29


B BASICS_MARCH 2023
Plotting simple graphs

ezcontourf(Z)

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 30


B BASICS_MARCH 2023
Plotting simple graphs
z=inline('-5./(1+x.^2+y.^2)');
ezsurf(z,[-3,3,-3,3])
print f8.jpg -djpeg

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 31


B BASICS_MARCH 2023
Plotting simple graphs

ezsurfc(Z,[-3,3,-3,3])
print resp9.jpg -djpeg

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 32


B BASICS_MARCH 2023
Plotting simple graphs
Subplot
H=subplot(m,n,p) or subplot(mnp) breaks the figure window
into an m by n matrix of axes, select the p th axes for the
current plot and returns the axis handle

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 33


B BASICS_MARCH 2023
Subplot

>t=linspace(0,20,500);
>y=2*cos(t)+cos(2*t);
>ydot=-2*sin(t)-(2)*sin((2)*t);
>subplot(3,2,1)
>plot(t,y);
>grid on
>subplot(3,2,2)
>plot(t,ydot)
>grid on
>subplot(3,1,2)
>plot(y,ydot)
>grid on
>subplot(3,1,3)
>plot(y,ydot)
>grid on

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 34


B BASICS_MARCH 2023
Review

Where to type commands (command window >>)


How to execute commands (Press return or enter)
What to do if the command is very long ( use …, max
4096 character)
How to name variables (begin with a letter, max 31 V6)
What is the precision of computation (Double precision)
How to control the display format of output (use format)
How to suppress the screen output (use ;)
How to set paged-screen display (use more on command)

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 35


B BASICS_MARCH 2023
Where and how to save results

save resp.mat amp,phi save variable amp,phi in file resp.mat


save mf rx ry rz save variable rx, ry, rz in defult file mf.mat
save xdata.dat x –ascii save variable x in the file
xdata.dat in 8 digit ASCII format
save Saves the entire workspace in the file matlab.mat
load mf Load the variable saved in the file mf
load load the variable saved in matlab.mat
S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 36
B BASICS_MARCH 2023
Matrix
a(i,j)
A(m:n,k:l)
A(:,5:20)
[m,n)=size(A)
A=zeros(m,n) Null matrix with size
m,m
A=[] Null matrix of any
size
A([1 3],:)=[] Delete 1st &3rd row
eye(m,m)

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 37


B BASICS_MARCH 2023
Appending a row and column vector

1 0 0
clc 1 0 0  0 
1 0
a=[1 0 0;0 1 0;0 0 1] a = 0 1 0  a1 = 
0 0 1
u=[4 5 7]; 0 0 1   
v=[7; 8; 5] 4 5 7
a1=[a;u] 1 0 0 7 
b=[a v] b =  0 1 0 8 
c=[] 1 0 1 5 
d=zeros(2,4) 0 0 0 0
d = 
S.K. Dwivedy  0 0
IITG/MECH/SKD_ME101_MATLA
0 0  38
B BASICS_MARCH 2023
v=
7
8
5
a1 =
1 0 0
0 1 0
0 0 1
4 5 7

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 39


B BASICS_MARCH 2023
b=
1 0 0 7
0 1 0 8
0 0 1 5
c=
[]
d=
0 0 0 0
0 0 0 0
S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 40
B BASICS_MARCH 2023
Deleting a row or column
>> a=[2 3 5; 5 6 8; 8 2 7];
>> a(2,:)=[]
a=
2 3 5
8 2 7

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 41


B BASICS_MARCH 2023
>> b=[2 3 5 7 9; 5 6 8 5 8; 8 6 2 7 7;5 3 7 2 6];
b=
2 3 5 7 9
5 6 8 5 8
8 6 2 7 7
5 3 7 2 6
>> b(:,3:5)=[]
b =2 3
5 6
8 6
5 3
S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 42
B BASICS_MARCH 2023
>> eye(3,5)
ans =
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
>> ones(3,3)
ans =
1 1 1
1 1 1
1 1 1
S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 43
B BASICS_MARCH 2023
Special matrices

Hadamard,
hankel,
hilb,
invhilb, >Help specmat
kron,
pascal,
Toeplitz,
vander,
magic
S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 44
B BASICS_MARCH 2023
Some functions

>> linspace(0,10,4)
ans =
0 3.3333 6.6667 10.0000

>> logspace(0,3,4)
ans =

1 10 100 1000

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 45


B BASICS_MARCH 2023
>> a=[3 6 8; 4 8 2; 9 2 6];
>> eig(a)
ans =
16.0000
-4.6235
5.6235
>> [eigvec,eigval]=eig(a)
eigvec =
-0.6097 -0.7682 0.1446
-0.4653 0.1446 -0.7682
-0.6417 0.6236 0.6236
eigval =
16.0000 0 0
0 -4.6235 0
S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 46
0 0 5.6235B BASICS_MARCH 2023
Programming in Matlab

Write the programs using .m files

Script file
Write all valid matlab command in a file and save it as
.m file (e.g., amp.m).
All the variables are global variables
Results obtained from executing the script file are left
in the workspace.
Execute it by typing the file name (e.g., >amp)

Never name a script file in the name of a variable it computes


S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 47
B BASICS_MARCH 2023
function file

A function file is also an m-file, like script file, except that the
variables are local (name should be same as the function name)

A function file begins with a function definition line, which has a


well defined input and outputs
function [xout,yout]=functionname(xin,yin);
function [omega_n,amp]=mfw(m,k,c,f,omega);
function [amp]=mfw(m,k,c,f,omega);
function amp=mfw(m,k,c,f,omega);
function []=mfw(m,k,c,f,omega);
function mfw(m,k,c,f,omega);
S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 48
B BASICS_MARCH 2023
f =inline('r^3+2*r-10')
f=
Inline function:
f(r) = r^3+2*r-10

eval=Execute a string containing a MATLAB


expression

feval=Function evaluation

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 49


B BASICS_MARCH 2023
output=fzero(‘function’, value of the input variable)

>> f =inline('r^3+2*r-10');
>> Output=fzero(f,2)
Output =
1.8474
function f= bar1(r)
f =r^3+2*r-10;
>>a=fzero(@bar1,2)
a=
1.8474
S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 50
B BASICS_MARCH 2023
For loops

sum=0.0;
sum=0.0;
for m=1:1:10
for m=1:100
sum=sum+m;
sum=sum+m;
end
end
sum=
sum=
55
5050

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 51


B BASICS_MARCH 2023
While loop

clc;
v=1; num=1; i=1;
while num<300
num=3^i; v=[v;num]; i=i+1;
end
>> v'
ans =
1 3 9 27 81 243 729
S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 52
B BASICS_MARCH 2023
If-elseif-else statement
clc;
i=4;j=20;
if i>5 k=i;
elseif (i>1)&(j==20) k=5*i+j;
else k=1;
end
k
40

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 53


B BASICS_MARCH 2023
Solving linear equations

clc;
A=[1 2 3; 2 5 7; 7 8 3] % solve with Gaussian elimination

b=[10; 12; 15] A=[1 2 3; 2 5 7; 7 8 3];

x=A\b; b=[10; 12; 15]; C=[A b];

>>x = cr =rref ( C )

17.4167 1.0000 0 0 17.4167

-16.5833 0 1.0000 0 -16.5833

8.5833 0 0 1.0000 8.5833

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 54


B BASICS_MARCH 2023
•LU factorization
[ L, U] =lu (A);
•QR factorization
[ Q, R] =rq (A);
• Cholesky factorization
R=chol(A);
• Singular value decomposition
[U, V, D]=svd(A);

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 55


B BASICS_MARCH 2023
Integration
• Analytical integral
Integral=int(@fun,a,b)
•Numerical integration
Integral=quad or quadl or quad8(@fun,a,b,tol,p1,p2)

• Double integration
Integral=dblquad(‘fun’, xmin,xmax,ymin,ymax,tol)

F=inline(‘1-5*x^y’);
A=dblquad(F,0,2,-1,1)
S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 56
B BASICS_MARCH 2023
Integration
• For analytical integral
U=int(@fun,lowerlimit,upperlimit),
%------for example-----------

>> syms x

>> Z=exp(x)*cos(x)*x^2;

>> P=int(Z)

P=
(1/2*x^2-1/2)*exp(x)*cos(x)-(-
1/2*x^2+x-1/2)*exp(x)*sin(x)

>> P=int(Z,0,1)

P=

1/2
S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 57
B BASICS_MARCH 2023
•For numerical integration
Syntax
q = quad or quadl or quad8(fun,a,b)
q = quad or quadl or quad8(fun,a,b,tol)
%------------------Example-----------
>> F = @(x)1./(x.^3-2*x-5); >> F = inline('1./(x.^3-2*x-5)');
>> Q = quad(F,0,2) or >> Q = quad(F,0,2)
Q= Q=
-0.4605 -0.4605

Double integration
Syntax
q = dblquad(fun,xmin,xmax,ymin,ymax)
%------------------------ Example--------------------------
>> F = @(x,y)y*sin(x)+x*cos(y); >> F =inline('y*sin(x)+x*cos(y)');
>> Q = dblquad(F,pi,2*pi,0,pi) >> Q = dblquad(F,pi,2*pi,0,pi)
Q= Q=
-9.8696 -9.8696
>> >>
S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 58
B BASICS_MARCH 2023
Differentiation
Y = diff(Funtionname,variablename,numberofoder)
%..........................For Example……………………….
>> syms x y
>> syms x
>> Z=cos(x)*sin(y);
>> Z=cos(x);
>> Y=diff(Z,x) >> P=diff(Z,x)
Y= P=
-sin(x) -sin(x)*sin(y)

>> Y=diff(Z,x,2) >> P=diff(Z,y)


Y=
P=
-cos(x)
cos(x)*cos(y)
>> Y=diff(Z,x,3)
Y= >> P=diff(Z,y,2)
sin(x) P=
>> Q=exp(x)*cos(x);
>> R=diff(Q,x,2) >> Q=diff(diff(Z,x,2),y,2)
Y= Q=
S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 59
-2*exp(x)*sin(x) cos(x)*sin(y)
B BASICS_MARCH 2023
Solving the ordinary differential equations

Syntex
[t,Y] = solver(odefun,tspan,y0)
[t,Y] = solver(odefun,tspan,y0,options)
sol = solver(odefun,[t0 tf],y0...)
where solver is one of ode45, ode23, ode113, ode15s, ode23s, ode23t, or ode23tb.
#------------------For example-----------------How to solve the following ordinary
equation

This example explains and illustrates the steps you need to solve an initial value
ODE problem:
1.Rewrite the problem as a system of first-order ODEs. By substituting

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 60


B BASICS_MARCH 2023
2. Code the system of first-order ODEs:

The function must be of the form ydot = odefun(t,y)

function ydot = SaturT(t,y)

Ydot= [y(2); (1-y(1)^2)*y(2)-y(1)];

3. Apply a solver to the problem.

[t,y] = ode45(@SarurT,[0 20],[2; 0]);

4. View the solver output.


plot(t,y(:,1),'-',t,y(:,2),'--')
title('Solution of van der Pol Equation, \mu = 1');
xlabel('time t');
ylabel('solution y');
legend('y_1','y_2')
S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 61
B BASICS_MARCH 2023
THANK YOU

S.K. Dwivedy IITG/MECH/SKD_ME101_MATLA 62


B BASICS_MARCH 2023

You might also like