You are on page 1of 81

Workshop

Basics of MATLAB

A Lot of Techs
For the period 1-2 / 2/2019

1
• Introduction.
• Operation and equation.
• Plot in MATLAB.
• Vectors and matrices.
• Selection.
• Loops.
• Function.
2
Introduction

• MATLAB® is a programming platform designed specifically for engineers and


scientists. The heart of MATLAB is the MATLAB language, a matrix-based
language allowing the most natural expression of computational mathematics.
MATrix LABoratory

• What can you do with MATLAB?

•Analyze data
•Develop algorithms
•Create models and applications

• Who uses MATLAB?

Millions of engineers and scientists in industry and academia use MATLAB.


3
4
Operation and equation
• Arithmetic Operators
Symbol Role More Information
+ Addition plus
+ Unary plus uplus
- Subtraction minus
- Unary minus uminus
.* Element-wise multiplication times
* Matrix multiplication mtimes
./ Element-wise right division rdivide
/ Matrix right division mrdivide
.\ Element-wise left division ldivide
\ Matrix left division (also known as backslash) mldivide
.^ Element-wise power power
^ Matrix power mpower
5
• Relational Operators

Symbol Role More Information


== Equal to eq
~= Not equal to ne
> Greater than gt
>= Greater than or equal to ge
< Less than lt
<= Less than or equal to le

6
• Logical Operators

Symbol Role More Information


& Logical AND and
| Logical OR or
&& Logical AND (with short-circuiting) Logical Operators:
|| Logical OR (with short-circuiting) Short-Circuit && ||

~ Logical NOT not

7
• Special Variables and Constants
Name Meaning
Ans Most recent answer.
Eps Accuracy of floating-point precision.
i,j The imaginary unit √-1.
Inf Infinity.
NaN Undefined numerical result (not a number).
Pi The number π

8
• Hierarchy of arithmetic operations

Precedence Mathematical operations


First The contents of all parentheses are evaluated first, starting
from the innermost parentheses and working outward

Second All exponentials are evaluated, working from left to right

Third All multiplications and divisions are evaluated, working


from left to right

Fourth All additions and subtractions are evaluated, starting


from left to right

9
A−B/(K∗F−X^M)
2 1

3
4
5

10
• Operator Precedence
no Priority
1 Parentheses ()
2 Transpose (.'), power (.^), complex conjugate transpose ('), matrix power (^)
3 Unary plus (+), unary minus (-), logical negation (~)
4 Multiplication (.*), right division (./), left division (.\), matrix multiplication (*), matrix right division (/), matrix
left division (\)
5 Addition (+), subtraction (-)
6 Colon operator (:)
7 Less than (<), less than or equal to (<=), greater than (>), greater than or equal to
(>=), equal to (==), not equal to (~=)
8 Element-wise AND (&)
9 Element-wise OR (|)
10 Short-circuit AND (&&)
11 Short-circuit OR (||)

11
• Solve Algebraic
If eqn ,noitauqe na si solve(eqn, x) sevlos eqn elbairav cilobmys eht rof x.
Use the == operator to specify the familiar quadratic equation and solve it
using solve.
EX:-
syms a b c x
eqn = a*x^2 + b*x + c == 0;
solx = solve(eqn, x)

EX:-
syms a b c x
eqn = a*x^2 + b*x + c == 0;
solb = solve(eqn, b)

12
EX:- Find x?
𝑥𝑦 + 𝑦 2 − 5𝑥 + 7 = 0
syms x y
x=solve(x*y+y^2-5*x+7, x)

EX:- Find x?
𝑒 𝑥 − 2𝑥 + 1 = 0
syms x
x=solve(exp(x)-2*x+1, x)

13
EX:- Find x, y, z?

𝑥 − 2𝑦 + 𝑧 2 = 6
3𝑥 + 𝑦 3 − 𝑧 = 8
𝑥+𝑦+𝑧 =6
syms x y z
[x y z]=solve(x-2*y+z^2-6,3*x+y^3-z-8,x+y+z-6,x,y,z)

EX:- Find roots?

𝟐𝒙𝟒 + 𝟓𝒙𝟑 − 𝟏𝟑𝒙𝟐 + 𝟕 = 𝟎

roots([2 5 -13 0 7])

14
• Limit:

𝐥𝐢𝐦 𝒙
𝒙→𝒂

limit(expr,x,a)

𝑥 2 +4
EX:- 𝑦 = lim 3
𝑥→1 𝑥(𝑥 −4)
syms x
y=limit((x^2+4)/(x*(x^3-4)),x,1)

15
• differential and integral

Y = diff(X)
Y = diff(X,n)

EX:- d= diff ( x^4)

𝐝𝐟
EX:- 𝐈𝐟 𝐟 = 𝐱 𝟐 𝐬𝐢𝐧𝐱 , 𝐟𝐢𝐧𝐝 𝐝 =
𝐝𝐱
syms x
f=x^2*sin(x);
d=diff(f,x)

16
𝟐 𝟑 𝟒 𝛛𝟐 𝐟
EX:- 𝐈𝐟 𝐟 = 𝐱 𝐲 𝐳 , 𝐟𝐢𝐧𝐝 𝐝 =
𝛛𝐱 𝟐
syms x y z
f=x^2*y^3*z^4;
d=diff(f,x,2)

𝛛𝟐 𝐟
EX:- 𝐈𝐟 𝐟 = 𝐱𝟐𝐲𝟑𝐳𝟒, 𝐟𝐢𝐧𝐝 𝐝 =
𝛛𝐱𝛛𝐲
syms x y z
f=x^2*y^3*z^4;
d= diff(diff(f,y),x)

17
𝟐
EX:- solve the eq. d= ‫𝟏׬‬ 𝒙𝟐 − 𝟏 . 𝒅𝒙

syms x
d=int(x^2-1,x,1,2)

+∞ 𝟐
EX:- solve the eq. d= ‫𝟎׬‬ 𝒆−𝒙 . 𝒅𝒙

syms x
d=int(exp(-x^2),x,0,+inf)

18
𝟐 𝟏
EX:- solve the eq. d= ‫𝒚𝒙 𝟎׬ 𝟏׬‬. 𝒅𝒚𝒅𝒙

syms x y
d=int(int(x*y,y,0,1),x,1,2)

• NOTE:- Format of answer

>> x=-163.6667
If we want to see all 15 digits, we use the command format long

>> format long


>> x= -1.636666666666667e+002

To return to the standard format, enter format short, or simply format.


>> format short
19
𝟏
EX:- solve the eq. d= σ𝟐𝟎
𝒙=𝟏 𝒙

syms x
d =symsum(1/x,x,1,20)

𝟏
EX:- solve the eq. d= σ𝟐𝟎
𝒙=𝟏 𝒙!

syms x
d =symsum(1/factorial(x),x,1,20)

20
• Laplace & Inverse laplace

syms t s
F=laplace(f)
f=ilaplace(F)

EX:- find Laplace transform for f(t) =−𝟑. 𝟓𝒕 + 𝟓𝒆−𝟒𝒕 + 𝟖𝒄𝒐𝒔𝟐𝒕 + 𝟕𝒆−𝟑𝒕 𝒔𝒊𝒏𝟗𝒕
syms t s
f=-3.5*t+5*exp(-4*t)+8*cos(2*t)+7*exp(-3*t)*sin(9*t)
F=laplace(f)

21
EX:- find inverse Laplace transform for

𝟏𝟎 (𝒔+𝟏)
F(s) =
𝒔 𝒔𝟐 +𝒔+𝟓 (𝒔+𝟑)

syms t s
F= ( 10*(s+1))/(s*(s^2+s+5)*(s+3))
f=ilaplace(F)
simplify(f)
pretty(f)

22
Plot in MATLAB
EX:-
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)

EX:-
x = linspace(-2*pi,2*pi);
y1 = sin(x);
y2 = cos(x);
figure
plot(x,y1,x,y2)

23
EX:-
x = 0:pi/100:2*pi;
y1 = sin(x);
y2 = sin(x-0.25);
y3 = sin(x-0.5);
plot(x,y1,x,y2,'--',x,y3,':')

EX:-
x = 0:pi/10:2*pi;
y1 = sin(x);
y2 = sin(x-0.25);
y3 = sin(x-0.5);
plot(x,y1,'g',x,y2,'b--o',x,y3, 'r*')
legend('a','b','c')

24
title('name of plot')
xlabel('text')
ylabel('text')
axis([X0 X1 Y0 Y1])

EX:-
x = linspace(0,10);
y = cos(5*x);
plot(x,y,'r')
title('2-D Line Plot')
xlabel('x')
ylabel('cos(5x)')
axis([0 20 -2 2])

25
• Plotting Many Lines

plot(x,y,x,2*y)
plot(x,y,x,2*y,'--')

• Adding Plots
plot(x,y)
hold on
plot(5*x,5*y)

• Three-Dimensional Plots
t = 0:1:2*pi;
plot3(cos(3*t),sin(3*t),t)

26
• Line color

Option Description Equivalent RGB Triplet


'red' or 'r' Red [1 0 0]
'green' or 'g' Green [0 1 0]
'blue' or 'b' Blue [0 0 1]
'yellow' or 'y' Yellow [1 1 0]
'magenta' or 'm' Magenta [1 0 1]
'cyan' or 'c' Cyan [0 1 1]
'white' or 'w' White [1 1 1]
'black' or 'k' Black [0 0 0]
'none' No color Not applicable
27
• Line style, specified as one of the options listed in this table.

Line Style Description Resulting Line


'-' Solid line
'--' Dashed line
':' Dotted line
'-.' Dash-dotted line
'none' No line No line

28
EX:- 1

0.8

t = 0:0.1:2*pi; 0.6
cosine

y1 = cos(t); 0.4

y2 = sin(t); 0.2


sine

sin  , cos
plot(t,y1,t,y2) 0

xlabel('0 \leq \theta < 2\pi') -0.2

ylabel('sin \theta, cos \theta') -0.4

text(1,cos(1),' cosine') -0.6

text(3,sin(3),' sine') -0.8

box -1
0 1 2 3 4 5 6 7
0   < 2

29
• Subplot:

subplot(m,n,p)

EX:-
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)
30
EX:- x = linspace(0,10);
y1 = sin(x);
y2 = sin(5*x); 1 2

y3= cos(x); 0.5 1

y4= cos(5*x); 0 0

figure -0.5 -1

subplot(2,2,1); -1
0 5 10
-2
0 5 10 15
plot(x,y1)
subplot(2,2,2); 1 2

plot(x,y2) 0.5 1

axis([0 15 -2 2]) 0 0

subplot(2,2,3); -0.5 -1

plot(x,y3) -1 -2
0 5 10 0 5 10 15
subplot(2,2,4);
plot(x,y4)
axis([0 15 -2 2])
31
EX: - u = [0:8]
Vectors and matrices

u=
012345678

EX:- v = [0:2:8]

v=
02468

v(1:3)
ans = 0 2 4

v(1:2:4)
ans = 0 4
32
• Appending Vector
>> a= [ 1 2 3 4 ];
b = [5 6 7 8 ];
c = [a,b]
d = [a;b]

c=

1 2 3 4 5 6 7 8

d=

1 2 3 4
5 6 7 8

33
EX:- » A = [1 2 3; 3 4 5; 6 7 8]
A=
123
345
678

» A(2,3)
ans =
5

» A(1:2,2:3)
ans =
23
45

34
» A(:,2)
ans =
2
4
7

» A(3,:)
ans =
678

35
EX:- >> a = [ 1; 2; 3; 4 ];
b = [5; 6; 7; 8 ];
c = [a; b]
d = [a,b]

c =
1
2
3
4
5
6
7
8
d =

1 5
2 6
3 7
4 8
36
EX:- >> a = [ 1 2 3 ; 4 5 6; 7 8 9];
b = [ 7 5 6 ; 2 0 8; 5 7 1];
c=a+b
d=a-b
e=a/b
f = a*b

c=

8 7 9
6 5 14
12 15 10

37
d=
-6 -3 -3
2 5 -2
2 1 8

e=
-0.5254 0.6864 0.6610
-0.4237 0.9407 1.0169
-0.3220 1.1949 1.3729

f=
26 26 25
68 62 70
110 98 115

38
• Transpose of a Matrix

EX:- >> a = [ 10 12 23 ; 14 8 6; 27 8 9]
b = a'

a=
10 12 23
14 8 6
27 8 9

b=
10 14 27
12 8 8
23 6 9

39
• Matrix inverse

inv()

>> a=[1 2;3 4]


a=
1 2
3 4

>> inv(a)
ans =
-2.0000 1.0000
1.5000 -0.5000

40
• Concatenating Matrices

a = [ 10 12 23 ; 14 8 6; 27 8 9]
b = [ 12 31 45 ; 8 0 -9; 45 2 11]
c = [a, b]
d = [a; b]

• Determinant of a Matrix

a = [ 1 2 3; 2 3 4; 1 2 5]
det(a)

41
• Diagonal of a square Matrix
diag(A) Produce a vector consisting of diagonal of a square matrix A

a = [ 1 2 3; 2 3 4; 1 2 5]
diag(a)

a=
1 2 3
2 3 4
1 2 5
ans =
1
3
5

42
• eigenvalues and eigenvectors

eig(A)

[X,D]=eig(A)

X: full matrix whose columns are the corresponding eigenvectors


D: diagonal matrix with the eigenvalues on the main diagonal

EX:-
a = [ 1 2 3; 2 3 4; 1 2 5]
eig(a)
[X,D]=eig(a)

43
• Special Arrays in MATLAB
 zeros() function creates an array of all zeros
 ones() function creates an array of all ones
 eye() function creates an identity matrix
 rand() function creates an array of uniformly distributed random numbers on (0,1)

EX:-

zeros(5)
ones(4,3)
eye(4)
rand(3,5)

44
• Elementary functions

cos(x) Cosine
sin(x Sine
tan(x) Tangent
exp(x) Exponential round(x
sqrt(x) Square root rem(x)
abs(x) Absolute value
max(x) Maximum value
min(x) Minimum value

45
• Find
EX:-
X = [1 0 4 -3 0 0 0 8 6];
y = find(X) %returns linear indices for the nonzero entries of X. ( location )

y=
1 3 4 8 9

find(X > 2) %returns linear indices corresponding to the entries of X that are greater than 2.

ans =
3 8 9

46
• MAX
 max(A)
If A is a vector, max(A) returns the largest element in A.
If A is a matrix, max(A) treats the columns of A as vectors, returning a row vector
containing the maximum element from each column.

 C = max(A,[],dim)
 [C,I] = max(...)
 max(A,B)

47
EX:-
>> a=[1 20 30; 40 35 6;7 8 90]
max(a)
a=
1 20 30
40 35 6
7 8 90
ans =
40 35 90

>> max(a,[],2)
ans =
30
40
90

48
EX:-
>> a=[1 5 8 10 20 4]
b= [ 2 3 54 7 19 30]
[C,I] = max(a)
max(a,b)
a=
1 5 8 10 20 4
b=
2 3 54 7 19 30
C=
20
I=
5
ans =
2 5 54 10 20 30
49
• Sort
Sorts each column

EX:-
a=[ 2 8 4 9 10 5]

a=

2 8 4 9 10 5

>> sort(a)

ans =

2 4 5 8 9 10
50
EX:-
>> b=[ 1 5 4; 6 9 3; 7 8 2]
b=

1 5 4
6 9 3
7 8 2

>> sort(b)
ans =

1 5 2
6 8 3
7 9 4

51
• Sum
Sums each column.
EX:-
>> a=[ 2 8 4 9 10 5]

a=

2 8 4 9 10 5

>> sum(a)

ans =

38

52
EX:-

>> b=[ 1 5 4; 6 9 3; 7 8 2]

b=

1 5 4
6 9 3
7 8 2

>> sum(b)

ans =

14 22 9
53
• Reshape ( to change shape of matrix)

>> B = [1 2 3; 4 5 6; 7 8 9]

B=
1 2 3
4 5 6
7 8 9

>> C = reshape (B, 1, 9)


C=

1 4 7 2 5 8 3 6 9

54
• flipud( ) (to change matrix Up – Down)
• fliplr ( ) (to change matrix left – right)
>> a= [1 2 3;4 5 6;7 8 9]
a=
1 2 3
4 5 6
7 8 9
>> flipud(a)
ans =
7 8 9
4 5 6
1 2 3
>> fliplr (a )
ans =
3 2 1
6 5 4
9 8 7
55
• triu( ) (to get upper triangle with diagonal )
• tril( ) (to get lower triangle with diagonal )
• trace ( ) (to get the sum of diagonal )

EX:-
a=[ 1 2 3;4 5 6; 7 8 9]
triu(a)
tril(a)
trace(a)

56
Selection (Decision )
 if ... end statement
 if...else...end statement
 If... else if...else if...else...end statements
 nested if statements
 switch statement
 nested switch statements

• if condition
action1
else
action2
end

57
EX:-

𝑥 2 𝑖𝑓 𝑥 ≤ 5
F=
𝑥 3 +2 𝑖𝑓 𝑥 > 5

x=7;
if x<= 5
f=x^2
else
f=x^3+2
end

58
EX:-

a =5;
b =20;
if( a && b )
disp('good');
end
if( a || b )
disp('bad');
end

59
EX:-

a =0;
b =10;
if( a && b )
disp('good');
else
disp('bad');
end
if(~(a && b))
disp('Matlab');
end

60
EX:-

a = 100;
if a == 100
disp('excellent' );
elseif( a<100 && a>=50)
disp('pass' );
elseif (a>=0 && a<50)
disp('fail' );
else
disp('error');
end

61
62
x=input('Please input the value of x:');
y=input('Please input the value of y:');
z=0; w=0;
if (x>=2) & (y==0.5)
z=1/sqrt(2*pi*y/x)
elseif x==4
z=exp(-1*y/(2*x))/(log(y)*sqrt(x))
elseif (x>=10) & (y<8)
w=sin(x)
else
z=sqrt(x)+sqrt(y)
w=log(x)-3*log(y)
end

63
• switch statement

switch <switch_expression>
case <case_expression>
<statements>
case <case_expression>
<statements>
...
...
otherwise
<statements>
end

64
EX:-
grade = 'B';
switch(grade)
case 'A'
fprintf('Excellent!\n' );
case 'B'
fprintf(' very good\n' );
case 'C'
fprintf(' good\n' );
case 'D'
fprintf(' mid\n' );
case 'F'
fprintf(' bad\n' );
otherwise
fprintf('Invalid grade\n' );
end
65
Loops
 for loop
 while loop
 nested loops

• for loop

for index = start:increment:stop


statements
end

66
EX:-
>> for a = 10:20
fprintf('value of a: %d\n', a);
end
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 20
67
EX:-

>> for a = 1.0: -0.1: 0.0


disp(a)
end

EX:-

for a = [24,18,17,23,28]
disp(a)
end

68
EX:-
x = 1:10
for i=1:10
x2(i) = x(i)^2; better x2 = x.^2
end
x2

x=

1 2 3 4 5 6 7 8 9 10

x2 =

1 4 9 16 25 36 49 64 81 100

69
EX:-
x=-1:0.5:1;
for i=1:length(x)
if x(i) < 0.5
F(i) = x(i)^2;
else
F(i) = 0.3;
end
end
F
plot(x,F,'-k')

70
• while loop

while <expression>
<statements>
end

EX:-
a = 10;
while( a < 20 )
fprintf('value of a: %d\n', a);
a = a + 1;
end

71
EX:-
>> n=10;
a = 0;
while 2^a < n
a = a + 1;
end
>> a

a=

72
• nested loops

for m = 1:j
for n = 1:k
<statements>;
end
end

EX:-
for i=1:5,
for j=1:5,
a(i,j) = i+j;
end
end
a
73
while <expression1>
while <expression2>
<statements>
end
end

EX:-
i=1;
while( i<=5)
j=1;
while ( j<=5)
a(i,j) = i+j;
j=j+1;
end
i=i+1;
end
a
74
Function

• What is a MATLAB function?


A MATLAB “function” is a MATLAB program that performs a sequence of operations
specified
in a text file (called an m-file because it must be saved with a file extension of *.m). A
function
accepts one or more MATLAB variables as inputs, operates on them in some way, and then
returns one or more MATLAB variables as outputs and may also generate plots, etc.
(sometimes
a function doesn’t return any output variables but instead just generates plots, etc.).

75
• How do I Create a new MATLAB function?
Since an m-file is nothing more than a text file it can be created using any text editor –
however,
MATLAB provides its own editor that provides some particular features that are useful
when
writing/editing functions.
To open a new m-file: In the MATLAB command window, go to FILE on the toolbar, select
NEW, then select M-FILE. This opens the MATLAB editor/debugger and gives an empty
file in
which you can create whatever m-file you want.

76
• Function Definition

 function myfun
 function[out]= myfun(in)
 function[out1,out2,..., outN]= myfun(in1,in2,in3,..., inN)

77
EX:- write a function to find sum of any vector?

function [y]=summ(x)
z=length(x);
s=0;
for i=1:z
s= s+x(i);
end
y=s
end

>> x=[1 2 3 4 5 6 7 8 9 10];


>> y=summ(x);
y=
55
78
EX:-
function [area, circum] = areacirc(rad)
area = pi * rad * rad;
circum = 2 * pi * rad;

>> areacirc(3.4)
ans =
36.3168
>> [x,y]=areacirc(3.4)
x=
36.3168
y=
21.3628

79
>> [a c] = areacirc(1:4)

a=
3.1416 12.5664 28.2743 50.2655

c=
6.2832 12.5664 18.8496 25.1327

80
EX:- Define a function that accepts an input vector, calculates the average of the values,
and returns a single result.

function y = average(x)
if ~isvector(x)
error('Input must be a vector')
end
y = sum(x)/length(x);
end

>> z = 1:99;
average(z)

81

You might also like