80
INTRODUCTION TO MATLAB By K.Kiran Kumar Assistant professor Mechanical engineering department B.S.Abdur Rahman University Email:- [email protected] Ph.no:- 9047475841

Demo on Matlab

Embed Size (px)

Citation preview

Page 1: Demo on Matlab

INTRODUCTIONTO

MATLABBy

K.Kiran Kumar

Assistant professor

Mechanical engineering department

B.S.Abdur Rahman University

Email:- [email protected]

Ph.no:- 9047475841

Page 2: Demo on Matlab

WHAT IS MATLAB?

MATLAB (MATrix LABoratory) is basically a high level language

which has many specialized toolboxes for making things easier for us.

MATLAB is a program for doing numerical computation. It wasoriginally designed for solving linear algebra type problems usingmatrices. It‟s name is derived from MATrix LABoratory.

MATLAB has since been expanded and now has built-in functions forsolving problems requiring data analysis, signal processing, optimization,and several other types of scientific computations. It also containsfunctions for 2-D and 3-D graphics and animation.

Powerful, extensible, highly integrated computation, programming,visualization, and simulation package.

Widely used in engineering, mathematics, and science.

Why?

Page 3: Demo on Matlab

FEATURES

o MATLAB is an interactive system for doing

numerical computations. MATLAB makes use of

highly respected algorithms and hence you can be

confident about your results.

Powerful operations can be performed using just

one or two commands. You can also build your

own set of functions. Excellent graphics facilities

are included.

Page 4: Demo on Matlab

Intro MATLAB

MATLAB TOOLBOXES

Signal & Image Processing

Signal Processing

Image Processing

Communications

Frequency Domain Identification

Higher-Order Spectral Analysis

System Identification

Wavelet

Filter Design

Control Design

Control System

Fuzzy Logic

Robust Control

μ-Analysis and Synthesis

Model Predictive Control

Math and Analysis

Optimization

Requirements Management Interface

Statistics

Neural Network

Symbolic/Extended Math

Partial Differential Equations

PLS Toolbox

Mapping

Spline

Data Acquisition and Import

Data Acquisition

Instrument Control

Excel Link

Portable Graph Object

Page 5: Demo on Matlab

A simulation tool for dynamic systems

Simulink library Browser:

Collection of sources, system modules, sinks

SIMULINK

System

Input Output

Page 6: Demo on Matlab

Steps in creating a model Open the library of blocks (Library Browser)

► Icon on Matlab toolbar

► Matlab start button > Simulink > Library Browser

>> simulink % from Command Window

Open a new model (Icon on Library toolbar)

Drag blocks from Library to model window

Connect blocks with arrows

Edit parameters for blocks (double click on block)

Annotate with text as desired (double click at spot)

Run simulation by clicking on toolbar Run icon (►)

CONTD…..

Page 7: Demo on Matlab

WHAT ARE WE INTERESTED IN?

Matlab is too broad tool used in industry and Research

purposes also.

For our course purpose in this part of lab course we

will have brief review of basics and learn what can be

done with Matlab.

Page 8: Demo on Matlab

MATLAB SCREEN

Page 9: Demo on Matlab

VARIABLES

No need for types. i.e.,

int a;

double b;

float c;

Accuracy and comfort is very high with matlab codes.

>>x=5;

>>x1=2;

Page 10: Demo on Matlab

ARRAY, MATRIX

Page 11: Demo on Matlab

LONG ARRAY, MATRIX

Page 12: Demo on Matlab

GENERATING VECTORS FROM FUNCTIONS

Page 13: Demo on Matlab

MATRIX INDEX

Page 14: Demo on Matlab

OPERATORS (ARITHMETIC)

Page 15: Demo on Matlab

MATRICES OPERATIONS

Page 16: Demo on Matlab

THE “DOT OPERATOR”

By default and whenever possible MATLAB will perform true matrix operations (+ - *). The operands in every arithmetic expression are considered to be matrices.

If, on the other hand, the user wants the scalar version of an operation a “dot” must be put in front of the operator, e.g., .*. Matrices can still be the operands but the mathematical calculations will be performed element-by-element.

A comparison of matrix multiplication and scalar multiplication is shown on the next slide.

Page 17: Demo on Matlab

OPERATORS (ELEMENT BY ELEMENT)

Page 18: Demo on Matlab

Intro MATLAB

DOT OPERATOR EXAMPLE

>> A = [1 5 6; 11 9 8; 2 34 78]

A =

1 5 6

11 9 8

2 34 78

>> B = [16 4 23; 8 123 86; 67 259 5]

B =

16 4 23

8 123 86

67 259 5

Page 19: Demo on Matlab

Intro MATLAB

DOT OPERATOR EXAMPLE (CONT.)

>> C = A * B % “normal” matrix multiply

C =

458 2173 483

784 3223 1067

5530 24392 3360

>> CDOT = A .* B % element-by-element

CDOT =

16 20 138

88 1107 688

134 8806 390

Page 20: Demo on Matlab

THE USE OF “.” -OPERATION

Page 21: Demo on Matlab

MATLAB FUNCTIONS

Page 22: Demo on Matlab

COMMON MATH FUNCTIONS

Page 23: Demo on Matlab

BUILT-IN FUNCTIONS FOR HANDLING ARRAYS

Page 24: Demo on Matlab

MATLAB BUILT-IN ARRAY FUNCTIONS

Page 25: Demo on Matlab

Standard Arrays» eye(2)

ans =

1 0

0 1

» eye(2,3)

ans =

1 0 0

0 1 0

»

Other such arrays:

ones(n), ones(r, c)

zeros(n), zeros(r, c)

rand(n), rand(r,c)

Page 26: Demo on Matlab

RANDOM NUMBERS GENERATION

Page 27: Demo on Matlab

COMPLEX NUMBERS HANDLING

FUNCTIONS

Page 28: Demo on Matlab

2-D plotting functions

>> plot(x,y) % linear Cartesian

>> semilogx(x,y) % logarithmic abscissa

• uses base 10 (10n for axis units)

>> semilogy(x,y) % logarithmic ordinate

• uses base 10 (10n for axis units)

>> loglog(x, y) % log scale both dimensions

• uses base 10 (10n for axis units)

>> polar(theta,rho) % angular and radial

GRAPHICS AND DATA DISPLAY

Page 29: Demo on Matlab

2-D display variants

Cartesian coordinates>> bar(x,y) % vertical bar graph

>> barh(x,y) % horizontal bar graph

>> stem(x,y) % stem plot

>> area(x,y) % color fill from horizontal axis to line

>> hist(y,N) % histogram with N bins (default N = 10)

Polar coordinates>> pie(y)

>> rose(theta,N) % angle histogram, N bins (default 10)

CONTINUED..

Page 30: Demo on Matlab

3-D Plotting syntax

Line

>> plotfunction(vector1, vector2, vector3)

Vector lengths must be the same

► Example

>> a = 1:0.1:30;

>> plot3( sin(a), cos(a), log(a) )

Pie>> pie3(vector)

One dimensional data, but 3-D pie perspective

GRAPHICS AND DATA DISPLAY

Page 31: Demo on Matlab

3-D surface plotting functions

>> contour(x,y,Z) % projection into X-Y plane

>> surf(x,y,Z) % polygon surface rendering

>> mesh(x,y,Z) % wire mesh connecting vertices

>> waterfall(x,y,Z)

• like mesh but without column connection lines

• used for column-oriented data

GRAPHICS AND DATA DISPLAY

Page 32: Demo on Matlab

BASIC TASK: PLOT THE FUNCTION

SIN(X) BETWEEN 0≤X≤4Π

Page 33: Demo on Matlab

PLOT THE FUNCTION E-X/3SIN(X)

BETWEEN 0≤X≤4Π

Page 34: Demo on Matlab

PLOT THE FUNCTION e-X/3SIN(X)

BETWEEN 0≤X≤4Π

Page 35: Demo on Matlab

DISPLAY FACILITIES

Page 36: Demo on Matlab

CONTD..

Page 37: Demo on Matlab

LINE SPECIFIERS IN THE plot() COMMAND

Line Specifier Line Specifier Marker Specifier

Style Color Type

Solid - red r plus sign +

dotted : green g circle o

dashed -- blue b asterisk *

dash-dot -. Cyan c point .

magenta m square s

yellow y diamond d

black k

plot(x,y,‘line specifiers’)

Page 38: Demo on Matlab

MULTIPLE GRAPHS

t=0:pi/100:2*pi;

y1=sin(t);

y2=sin(t+pi/2);

plot(t,y1,t,y2);

grid on

0 1 2 3 4 5 6 7-1

-0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

0.8

1

Page 39: Demo on Matlab

MULTIPLE PLOTS

subplot(i,j,k)

• i is the number of rows of subplots in the plot• j is the number of columns of subplots in the plot• k is the position of the plot

t=0:pi/100:2*pi;

y1=sin(t);

y2=sin(t+pi/2);

subplot(2,2,1)

plot(t,y1)

grid on

subplot(2,2,2)

plot(t,y2);

grid on

0 2 4 6 8-1

-0.5

0

0.5

1

0 2 4 6 8-1

-0.5

0

0.5

1

Page 40: Demo on Matlab

Plots

» x = 1:2:50;

» y = x.^2;

» plot(x,y)

0 5 10 15 20 25 30 35 40 45 500

500

1000

1500

2000

2500

Page 41: Demo on Matlab

Plots

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

» xlabel('Values of x')

» ylabel('y')

0 5 10 15 20 25 30 35 40 45 500

500

1000

1500

2000

2500

Values of x

y

Page 42: Demo on Matlab

Plots

» P = logspace(3,7);

» Q = 0.079*P.^(-0.25);

» loglog(P,Q, '.-')

» grid

103

104

105

106

107

10-3

10-2

10-1

Page 43: Demo on Matlab

INTERESTING FEATURE OF GENERATING

SINE CURVE

x = 0:0.05:6;

y = sin(pi*x);

Y = (y >= 0).*y;

plot(x,y,':',x,Y,'-')

0 1 2 3 4 5 6-1

-0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

0.8

1

Page 44: Demo on Matlab

OPERATORS (RELATIONAL, LOGICAL)

Page 45: Demo on Matlab

POLYNOMIALS

Page 46: Demo on Matlab

MATLAB FUNCTIONS FOR POLYNOMIALS

Page 47: Demo on Matlab

Contd..

Representing Polynomials:x4 - 12x3 + 25x + 116» P = [1 -12 0 25 116];

» roots(P)

ans =

11.7473

2.7028

-1.2251 + 1.4672i

-1.2251 - 1.4672i

» r = ans;

» PP = poly(r)

PP =

1.0000 -12.0000 -0.0000 25.0000 116.0000

Page 48: Demo on Matlab

Polynomial Multiplication

a = x3 + 2x2 + 3x + 4b = 4x2 + 9x + 16

» a = [1 2 3 4];

» b = [4 9 16];

» c = conv(a,b)

c =

4 17 46 75 84 64

»

Page 49: Demo on Matlab

Evaluation of a

Polynomial

a = x3 + 2x2 + 3x + 4

» polyval(a, 2)

ans =

26

»

Page 50: Demo on Matlab

Polynomial Curve Fitting

» x = [1 3 7 21];

» y = [2 9 20 55];

» polyfit(x,y,2)

ans =

-0.0251 3.1860 -0.8502

Page 51: Demo on Matlab

Symbolic Math

» syms x

» int('x^3')

ans =

1/4*x^4

» eval(int('x^3',0,2))

ans =

4

»

Page 52: Demo on Matlab

Solving Nonlinear

Equationsnle.m

function f = nle(x)

% To solve

% f1(x1,x2) = x1^2 - 4x1^2 - x1x2 = 0

% f2(x1,x2) = 2x^2 - x2^2 + 3x1x2 = 0

f(1) = x(1) - 4*x(1)*x(1) - x(1)*x(2);

f(2) = 2*x(2) - x(2)*x(2) + 3*x(1)*x(2);

Program:-

» x0 = [1 1]';

» x = fsolve('nle', x0)

Solution:-

x =

0.2500

0.0000

Page 53: Demo on Matlab

TO FIND EIGEN VALUES AND EIGEN

VECTORS OF MATRICES

Page 54: Demo on Matlab

CONTINUED…

Page 55: Demo on Matlab

WHAT IS THE TIME YOU TAKE TO SOLVE

LINEAR EQUATIONS

Solve manually and tell me what is the answer..?

That is find out x=

y=

z=

Page 56: Demo on Matlab

SOLVING SET OF SIMULTANEOUS

EQUATIONS

Page 57: Demo on Matlab

DIFFERENTATION

Page 58: Demo on Matlab

SOLVING DIFFERENTIAL EQUATIONS

Page 59: Demo on Matlab

PERFORMING INTEGRATION

Page 60: Demo on Matlab

FLOW CONTROL

Page 61: Demo on Matlab

CONTROL STRUCTURES

Page 62: Demo on Matlab

CONTROL STRUCTURES

Page 63: Demo on Matlab

CONTROL STRUCTURES

Page 64: Demo on Matlab

IF STATEMENT

n = input(„Enter the upper limit: „);

if n < 1

disp („Your answer is meaningless!‟)

end

x = 1:n;

term = sqrt(x);

y = sum(term)

Jump to here if TRUE

Jump to here if FALSE

Page 65: Demo on Matlab

EXAMPLE PROGRAM TO EXPLAIN IF LOOP

% Program to find whether roots are imaginary or not%

clc;

clear all;

a=input('enter value of a:');

b=input('enter value of b:');

c=input('enter value of c:');

discr = b*b - 4*a*c;

if discr < 0

disp('Warning: discriminant is negative, roots are imaginary');

end

Solution:-

Input:

enter value of a:1

enter value of b:2

enter value of c:3

Output:

Warning: discriminant is negative, roots are imaginary

Page 66: Demo on Matlab

EXAMPLE OF IF ELSE STATEMENT

>> A = 2; B = 3;

>> if A > B

'A is bigger'

elseif A < B

'B is bigger'

elseif A == B

'A equals B'

else

error('Something odd is happening')

end

ans =

B is bigger

Page 67: Demo on Matlab

IF STATEMENT EXAMPLE

Here are some examples based on the familiar quadratic formula.

1. discr = b*b - 4*a*c;

if discr < 0

disp('Warning: discriminant is negative, roots are imaginary');

end

2. discr = b*b - 4*a*c;

if discr < 0

disp('Warning: discriminant is negative, roots are imaginary');

else

disp('Roots are real, but may be repeated')

end

3. discr = b*b - 4*a*c;

if discr < 0

disp('Warning: discriminant is negative, roots are imaginary');

elseif discr == 0

disp('Discriminant is zero, roots are repeated')

else

disp('Roots are real')

end

Page 68: Demo on Matlab

EXAMPLE OF FOR LOOP

a.)

for ii=1:5

x=ii*ii

end

Solution:-

X= 1 4 9 16 25

b.)

Problem: Draw graphs of sin(nπ x) on the interval −1 ≤ x ≤ 1 for

n = 1,2,....,8.We could do this by giving 8 separate plot

commands but it is much easier to use a loop.

Program:-

x=-1:0.05:1;

for n=1:8

subplot(4,2,n);

plot(x, sin(n*pi*x));

end

-1 -0.5 0 0.5 1-1

0

1

-1 -0.5 0 0.5 1-1

0

1

-1 -0.5 0 0.5 1-1

0

1

-1 -0.5 0 0.5 1-1

0

1

-1 -0.5 0 0.5 1-1

0

1

-1 -0.5 0 0.5 1-1

0

1

-1 -0.5 0 0.5 1-1

0

1

-1 -0.5 0 0.5 1-1

0

1

Page 69: Demo on Matlab

EXAMPLE OF FOR & WHILE LOOP

% example of for loop%

Program:-

for ii=1:5

x=ii*ii

End

Solution:

1 4 9 16 25

%example of while loop%

Program:-

x = 1

while x <= 10

x = 3*x

End

Solution:

x=1 x=3 x= 9 x=27

Code:-

x = 1

while x <= 100

x = 3*x

end

Solution:-

X= 1 3 9 27

Page 70: Demo on Matlab

GENERATION OF FIBONACCI SERIES AND PLOT

clc;

clear all

hold off;

F(1) = 0;

F(2) = 1;

for i = 3:20

F(i) = F(i-1) + F(i-2);

end

plot(1:19, F(1:19)./F(2:20),'o' )

xlabel('n')

hold on

plot(1:19, F(1:19)./F(2:20),'-' )

legend('Ratio of terms f_{n-1}/f_n')

plot([0 20], (sqrt(5)-1)/2*[1,1],'--')

hold off

0 2 4 6 8 10 12 14 16 18 200

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

0.9

1

n

Ratio of terms fn-1

/fn

The Fibonnaci sequence starts off with the numbers

0 and 1, then succeeding terms are the sum of its

two immediate predecessors.

Mathematically, f1 = 0, f2 = 1 and

fn = fn−1 + fn−2 , n = 3, 4,5,......

Page 71: Demo on Matlab

WHILE LOOP EXAMPLES

Problem 1.

Program:-

S = 1;

n = 1;

while S+(n+1)^2 < 100

n = n+1;

S = S + n^2;

end

[n,S]

Solution:-

ans = 6 91

Page 72: Demo on Matlab

CONTINUED…

Find the approximate root of the equation x = cos x .We can do this by making a guess x1 = π / 4 ,say,

then computing the sequence of values

xn = cos xn−1 , n = 2, 3, 4,....... and continuing until the difference between two successive

values xn − xn−1 is small enough.

Program:-

x = zeros(1,20); x(1) = pi/4;

n = 1; d = 1;

while d > 0.001

n = n+1; x(n) = cos(x(n-1));

d = abs(x(n)-x(n-1));

End

Solution:-

n = 14

x =

Columns 1 through 9

0.7854 0.7071 0.7602 0.7247 0.7487 0.7326 0.7435 0.7361 0.7411

Columns 10 through 18

0.7377 0.7400 0.7385 0.7395 0.7388 0 0 0 0

Columns 19 through 20

0 0

Page 73: Demo on Matlab

SWITCH STATEMENT EXAMPLE

Program:-n=input(„enter the value of n: ‟);

switch(rem(n,3))

case 0

m = 'no remainder'

case 1

m = „the remainder is one'

case 2

m = „the remainder is two'

otherwise

error('not possible')

end

Solution:-enter the value of n: 8

m =the remainder is two

Page 74: Demo on Matlab

Last but not least…!

Excellent topic on Plotting userdefined

observations of the theoritical and

Experimental observations

FORMATTING PLOTS

A plot can be formatted to have a required appearance.

With formatting you can:

Add title to the plot.

Add labels to axes.

Change range of the axes.

Add legend.

Add text blocks.

Add grid.

Page 75: Demo on Matlab

FORMATTING PLOTS

There are two methods to format a plot:

1. Formatting commands.

In this method commands, that make changes or additions to the

plot, are entered after the plot() command. This can be done in

the Command Window, or as part of a program in a script file.

2. Formatting the plot interactively in the Figure Window.

In this method the plot is formatted by clicking on the plot and

using the menu to make changes or add details.

Page 76: Demo on Matlab

FORMATTING COMMANDS

title(‘string’)

Adds the string as a title at the top of the plot.

xlabel(‘string’)

Adds the string as a label to the x-axis.

ylabel(‘string’)

Adds the string as a label to the y-axis.

axis([xmin xmax ymin ymax])

Sets the minimum and maximum limits of the x- and y-axes.

Page 77: Demo on Matlab

FORMATTING COMMANDS

legend(‘string1’,’string2’,’string3’)

Creates a legend using the strings to label various curves (when

several curves are in one plot). The location of the legend is

specified by the mouse.

text(x,y,’string’)

Places the string (text) on the plot at coordinate x,y relative to the

plot axes.

gtext(‘string’)

Places the string (text) on the plot. When the command executes

the figure window pops and the text location is clicked with the

mouse.

Page 78: Demo on Matlab

EXAMPLE PROGRAM

clc;

clear all;

x=[10:0.1:22];

y=95000./x.^2;

xd=[10:2:22];

yd=[950 640 460 340 250 180 140];

plot(x,y,'-','LineWidth',1.0)

hold on

plot(xd,yd,'ro--','linewidth',1.0,'markersize',10)

hold off

xlabel('DISTANCE (cm)')

ylabel('INTENSITY (lux)')

title('\fontname{Arial}Light Intensity as a Function of Distance','FontSize',14)

axis([8 24 0 1200])

text(14,700,'Comparison between theory and

experiment.','EdgeColor','r','LineWidth',2)

legend('Theory','Experiment',0)

8 10 12 14 16 18 20 22 240

200

400

600

800

1000

1200

DISTANCE (cm)

INT

EN

SIT

Y (

lux)

Light Intensity as a Function of Distance

Comparison between theory and experiment.

Theory

Experiment

Page 79: Demo on Matlab

MATLAB OPEN RESOURCES

www.mathworks.com/

www.mathtools.net/MATLAB

www.math.utah.edu/lab/ms/matlab/matlab.html

web.mit.edu/afs/athena.mit.edu/software/matlab/

www.utexas.edu/its/rc/tutorials/matlab/

www.math.ufl.edu/help/matlab-tutorial/

www.indiana.edu/~statmath/math/matlab/links.html

www.eng.cam.ac.uk/help/tpl/programs/matlab.html

Page 80: Demo on Matlab

THANK YOU…

Any Questions ?