Introduction to matlab i
This presentation is the property of its rightful owner.
Sponsored Links
1 / 57

Introduction to MATLAB I PowerPoint PPT Presentation


  • 87 Views
  • Uploaded on
  • Presentation posted in: General

Introduction to MATLAB I. MATLAB. MATLAB is a program for doing numerical computation. It was originally designed for solving linear algebra type problems using matrices. It’s name is derived from MATrix LABoratory.

Download Presentation

Introduction to MATLAB I

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Introduction to matlab i

Introduction to MATLAB I


Matlab

MATLAB

  • MATLAB is a program for doing numerical computation. It was originally designed for solving linear algebra type problems using matrices. It’s name is derived from MATrix LABoratory.

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


Software development philosophy

Software Development Philosophy

  • Major software characteristics:

    • matrix-based numeric computation

    • high-level programming language

    • graphics & visualization

    • toolboxes provide application-specific functionality

    • BASIC-like syntax, with elements from C, GUI IDE

    • basic data type: 2- or 3-dimensional floating-point matrix

    • most operators and functions work on entire matrices

  • Open & extensible system architecture

  • Interfaces to other systems

    • Custom C, Fortran

    • Extensive data I/O facility


Availability and d ocumentation

Availability and Documentation

  • Installed on:

    • Windows (or Linux)

  • Full documentation available online in HTML and PDF:

    • Start Matlab then type helpdesk

    • http://www.mathworks.com/access/helpdesk/help/helpdesk.html

  • Read “Getting Started” section of the MATLAB manual

  • Use the command help function-name


Matlab windows

MATLAB Windows

  • Command Window

    • enter commands and data

    • print results

  • Graphics Window

    • display plots and graphs

  • Edit Window

    • create and modify m-files


Matlab1

MATLAB

  • The MATLAB environment is command oriented somewhat like UNIX. A prompt appears on the screen and a MATLAB statement can be entered. When the <ENTER> key is pressed, the statement is executed, and another prompt appears.

  • If a statement is terminated with a semicolon ( ; ), no results will be displayed. Otherwise results will appear before the next prompt.

  • The following slide is the text from a MATLAB screen.


Matlab2

MATLAB

To get started, type one of these commands: helpwin, helpdesk, or demo

» a=5;

» b=a/2

b =

2.5000

»


Matlab variable names

MATLAB Variable Names

  • Variable names ARE case sensitive

  • Variable names can contain up to 63 characters (as of MATLAB 6.5 and newer)

  • Variable names must start with a letter followed by letters, digits, and underscores.


Matlab special variables

MATLAB Special Variables

ansDefault variable name for results

piValue of 

epsSmallest incremental number

infInfinity

NaNNot a numbere.g. 0/0

i and ji = j = square root of -1

realminThe smallest usable positive real number

realmaxThe largest usable positive real number


Matlab math assignment operators

MATLAB Math & Assignment Operators

Power^or.^a^bor a.^b

Multiplication* or.*a*bora.*b

Division/or./a/bora./b

or\or.\b\aorb.\a

NOTE: 56/8 = 8\56

- (unary) + (unary)

Addition+ a + b

Subtraction- a - b

Assignment=a = b (assign b to a)


Other matlab symbols

Other MATLAB symbols

>>prompt

. . .continue statement on next line

,separate statements and data

%start comment which ends at end of line

;(1)suppress output

(2)used as a row separator in a matrix

:specify range


Matlab matrices

MATLAB Matrices

  • MATLAB treats all variables as matrices. For our purposes a matrix can be thought of as an array, in fact, that is how it is stored.

  • Vectors are special forms of matrices and contain only one row OR one column.

  • Scalars are matrices with only one row AND one column


Matlab matrices1

MATLAB Matrices

  • A matrix with only one row AND one column is a scalar. A scalar can be created in MATLAB as follows:

    » a_value=23

    a_value =

    23


Matlab matrices2

MATLAB Matrices

  • A matrix with only one row is called a row vector. A row vector can be created in MATLAB as follows (note the commas):

    » rowvec = [12 , 14 , 63]

    rowvec =

    12 14 63


Matlab matrices3

MATLAB Matrices

  • A matrix with only one column is called a column vector. A column vector can be created in MATLAB as follows (note the semicolons):

    » colvec = [13 ; 45 ; -2]

    colvec =

    13

    45

    -2


Matlab matrices4

MATLAB Matrices

  • A matrix can be created in MATLAB as follows (note the commas AND semicolons):

    » matrix = [1 , 2 , 3 ; 4 , 5 ,6 ; 7 , 8 , 9]

    matrix =

    1 2 3

    4 5 6

    7 8 9


Extracting a sub matrix

Extracting a Sub-Matrix

  • A portion of a matrix can be extracted and stored in a smaller matrix by specifying the names of both matrices and the rows and columns to extract. The syntax is:

    sub_matrix = matrix ( r1 : r2 , c1 : c2 ) ;

    where r1 and r2 specify the beginning and ending rows and c1 and c2 specify the beginning and ending columns to be extracted to make the new matrix.


Matlab matrices5

A column vector can be extracted from a matrix. As an example we create a matrix below:

» matrix=[1,2,3;4,5,6;7,8,9]

matrix =

1 2 3

4 5 6

7 8 9

Here we extract column 2 of the matrix and make a column vector:

» col_two=matrix( : , 2)

col_two =

2

5

8

MATLAB Matrices


Matlab matrices6

A row vector can be extracted from a matrix. As an example we create a matrix below:

» matrix=[1,2,3;4,5,6;7,8,9]

matrix =

1 2 3

4 5 6

7 8 9

Here we extract row 2 of the matrix and make a row vector. Note that the 2:2 specifies the second row and the 1:3 specifies which columns of the row.

» rowvec=matrix(2 : 2 , 1 : 3)

rowvec =

4 5 6

MATLAB Matrices


Reading data from files

Reading Data from files

  • MATLAB supports reading an entire file and creating a matrix of the data with one statement.

    >> load mydata.dat;% loads file into matrix.

    % The matrix may be a scalar, a vector, or a

    % matrix with multiple rows and columns. The

    % matrix will be named mydata.

    >> size (mydata)% size will return the number

    % of rows and number of

    % columns in the matrix

    >> length (myvector)% length will return the total

    % no. of elements in myvector


Plotting with matlab

Plotting with MATLAB

  • MATLAB will plot one vector vs. another. The first one will be treated as the abscissa (or x) vector and the second as the ordinate (or y) vector. The vectors have to be the same length.

  • MATLAB will also plot a vector vs. its own index. The index will be treated as the abscissa vector. Given a vector “time” and a vector “dist” we could say:

    >> plot (time, dist) % plotting versus time

    >> plot (dist)% plotting versus index


Plotting with matlab1

Plotting with MATLAB

  • There are commands in MATLAB to "annotate" a plot to put on axis labels, titles, and legends. For example:

    >> % To put a label on the axes we would use:

    >> xlabel ('X-axis label')

    >> ylabel ('Y-axis label')

    >> % To put a title on the plot, we would use:

    >> title ('Title of my plot')


Plotting with matlab2

Plotting with MATLAB

  • Vectors may be extracted from matrices. Normally, we wish to plot one column vs. another. If we have a matrix “mydata” with two columns, we can obtain the columns as a vectors with the assignments as follows:

    >> first_vector = mydata ( : , 1) ; % First column

    >> second_vector = mydata ( : , 2) ; % Second one

    >>% and we can plot the data

    >> plot ( first_vector , second_vector )


Some useful matlab commands

Some Useful MATLAB commands

  • whoList known variables

  • whosList known variables plus their size

  • helpEx: >> help sqrt Help on using sqrt

  • lookforEx: >> lookfor sqrt Search for

    keyword sqrt in m-files

  • what Ex:>> what a: List MATLAB files in a:

  • clearClear all variables from work space

  • clear x yClear variables x and y from work space

  • clcClear the command window


Some useful matlab commands1

Some Useful MATLAB commands

  • whatList all m-files in current directory

  • dirList all files in current directory

  • lsSame as dir

  • type testDisplay test.m in command window

  • delete testDelete test.m

  • cd a:Change directory to a:

  • chdir a:Same as cd

  • pwdShow current directory

  • which testDisplay current directory path to test.m

  • whyIn case you ever needed a reason


Matlab relational operators

MATLAB Relational Operators

  • MATLAB supports six relational operators.

    Less Than<

    Less Than or Equal<=

    Greater Than>

    Greater Than or Equal>=

    Equal To==

    Not Equal To~=


Matlab logical operators

MATLAB Logical Operators

  • MATLAB supports three logical operators.

    not~% highest precedence

    and&% equal precedence with or

    or|% equal precedence with and


Matlab logical functions

MATLAB Logical Functions

  • MATLAB also supports some logical functions.

    xor (exclusive or) Ex: xor (a, b)

    Where a and b are logical expressions. The xor operator evaluates to true if and only if one expression is true and the other is false. True is returned as 1, false as 0.

    any (x) returns 1 if any element of x is nonzero

    all (x) returns 1 if all elements of x are nonzero

    isnan (x) returns 1 at each NaN in x

    isinf (x) returns 1 at each infinity in x

    finite (x) returns 1 at each finite value in x


Matlab display formats

MATLAB Display formats

  • MATLAB supports 8 formats for outputting numerical results.

    format long16 digits

    format short e5 digits plus exponent

    format long e16 digits plus exponent

    format hexhexadecimal

    format banktwo decimal digits

    format +positive, negative or zero

    format ratrational number (215/6)

    format shortdefault display


Matlab selection structures

Matlab Selection Structures

  • An if - elseif - else structure in MATLAB.

    Note that elseif is one word.

    ifexpression1% is true

    % execute these commands

    elseif expression2% is true

    % execute these commands

    else% the default

    % execute these commands

    end


Matlab repetition structures

MATLAB Repetition Structures

  • A for loop in MATLAB for x = array

    for x = 1: 0.5 : 10

    % execute these commands

    end

  • A while loop in MATLABwhile expression

    while x <= 10

    % execute these commands

    end


Scalar matrix addition

Scalar - Matrix Addition

» a=3;

» b=[1, 2, 3;4, 5, 6]

b =

1 2 3

4 5 6

» c= b+a% Add a to each element of b

c =

4 5 6

7 8 9


Scalar matrix subtraction

Scalar - Matrix Subtraction

» a=3;

» b=[1, 2, 3;4, 5, 6]

b =

1 2 3

4 5 6

» c = b - a %Subtract a from each element of b

c =

-2 -1 0

1 2 3


Scalar matrix multiplication

Scalar - Matrix Multiplication

» a=3;

» b=[1, 2, 3; 4, 5, 6]

b =

1 2 3

4 5 6

» c = a * b % Multiply each element of b by a

c =

3 6 9

12 15 18


Scalar matrix division

Scalar - Matrix Division

» a=3;

» b=[1, 2, 3; 4, 5, 6]

b =

1 2 3

4 5 6

» c = b / a % Divide each element of b by a

c =

0.3333 0.6667 1.0000

1.3333 1.6667 2.0000


Calculations at the command line

Calculations at the Command Line

Assigning Variables

  • a = 2;

  • b = 5;

  • a^b

  • ans =

  • 32

  • x = 5/2*pi;

  • y = sin(x)

  • y =

  • 1

  • z = asin(y)

  • z =

  • 1.5708

Semicolon suppresses screen output

Results assigned to “ans” if name not given

Use parentheses ( ) for function inputs

Numbers stored in double-precision floating point format


Matlab matrices 1

In MATLAB, a matrix is a rectangular array of numbers

Scalars: 1-by-1 matrices

Vectors: matrices with only one row or column

Matrix elements can consist either of numbers (numeric arrays) or characters (string arrays)

Colon generates number sequence:

>> 11:14

ans =

11 12 13 14

Specify step size with second colon:

>> 1:3:12

ans =

1 4 7 10

MATLAB matrices (1)


Matlab matrices 2

Columns

(n)

1 2 3 4 5

A (2,4)

1

2

Rows (m) 3

4

5

A (17)

MATLAB matrices (2)

A =

16111621

27121722

38131823

49141924

510152025

4

10

1

6

2

8

1.2

9

4

25

7.2

5

7

1

11

0

0.5

4

5

56

23

83

13

0

10

Rectangular Matrix:

Scalar:1-by-1 array

Vector:m-by-1 array

1-by-n array

Matrix:m-by-n array

Matrix elements can be EITHER numbers OR characters


Matlab matrices 3

MATLAB matrices (3)

Row separator:

semicolon (;)

Column separator:

space / comma (,)

Use square brackets [ ]

  • a=[1 2;3 4]

  • a =

  • 1 2

  • 3 4

  • b=[-2.8, sqrt(-7), (3+5+6)*3/4]

  • b =

  • -2.8000 0 + 2.6458i 10.5000

  • b(2,5) = 23

  • b =

  • -2.8000 0 + 2.6458i 10.5000 0 0

  • 0 0 0 0 23.0000

Matrices must

be rectangular. (Undefined elements set to zero)

Any MATLAB expression can be entered as a matrix element


Matlab matrices 4

MATLAB matrices (4)

Array Subscripting / Indexing

1 2 3 4 5

A =

16111621

27121722

38131823

49141924

510152025

4

10

1

6

2

1

2

3

4

5

8

1.2

9

4

25

A(1:5,5)

A(:,5)

A(21:25)

A(1:end,end)

A(:,end)

A(21:end)’

7.2

5

7

1

11

0

0.5

4

5

56

A(3,1)

A(3)

23

83

13

0

10

A(4:5,2:3)

A([9 14;10 15])

  • Use () parentheses to specify index

  • colon operator (:) specifies range / ALL

  • [ ] to create matrix of index subscripts

  • 'end' specifies maximum index value


Matrices linear algebra

Matrices & Linear Algebra

  • help ops

  • help matfun


Matrix multiplication

Matrix Multiplication

  • Inner dimensions must be equal

  • Dimension of resulting matrix = outermost dimensions of multiplied matrices

  • Resulting elements = dot product of the rows of the 1st matrix with the columns of the 2nd matrix

  • a = [1 2 3 4; 5 6 7 8];

  • b = ones(4,3);

  • c = a*b

  • c =

  • 10 10 10

  • 26 26 26

[2x4]

[4x3]

[2x4]*[4x3] [2x3]

a(2nd row).b(3rd column)


Matrix multiplication1

Matrix Multiplication

X = X11 X12

X21 X22

Y = Y11 Y12

Y21 Y22

Then:

X*Y = Xrow1.Ycol1 Xrow1.Ycol2

Xrow2.Ycol1 Xrow2.Ycol2

= (X11*Y11)+(X12*Y21) (X11*Y12)+(X12*Y22)

(X21*Y11)+(X22*Y21) (X21*Y12)+(X22*Y22)


Matrix transpose

Matrix Transpose


Example solving equations using left division

Example: Solving Equationsusing “Left Division”

  • Solve this set of simultaneous equations:

  • A = [-1 1 2; 3 -1 1;-1 3 4];

  • b = [2;6;4];

  • x = inv(A)*b%If “A” is a square matrix

  • x =

  • 1.0000

  • -1.0000

  • 2.0000

  • x = A\b%underdetermined and overdetermined system

  • x =

  • 1.0000 %x1

  • -1.0000 %x2

  • 2.0000 %x3

-x1 + x2 + 2x3 = 2

3x1 - x2 + x3 = 6

-x1 + 3x2 + 4x3 = 4


Matlab functions

Matlab Functions

  • % Matlab Functions

  • % functions(a,x,y);

  • % a = 1 for dividing, a = 2 for multiplication,

  • % a = 3 for adding, a = 4 for subtraction

  • % calculations x/y , x*y , x-y , x+y

  • function [s] = functions_all(a,x,y)

  • if a==1;

  • s=x/y;

  • elseif a==2

  • s=x*y;

  • elseif a==3

  • s=x+y;

  • elseif a==4

  • s=x-y;

  • else

  • disp('a should be 1-2-3-4 ');

  • disp(' please try again ');

  • end


Built in functions

Built-in Functions

  • Sqrt( ), abs( ), sin( ), cos( ), exp( ), tanh( ), acos( ), log( ), log10( ), etc.

  • These operators are vectorized


Built in functions1

Built-in Functions

  • Certain functions, such as exponential and square root, have matrix definition also

  • Use “help expm” and “help sqrtm” for details

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

A =

1 3 5

2 4 6

-3 2 -1

>> B = sqrt(A)

B =

1.0000 1.7321 2.2361

1.4142 2.0000 2.4495

0 + 1.7321i 1.4142 0 + 1.0000i

>> C = sqrtm(A)

C =

2.1045 + 0.0000i 0.1536 - 0.0000i 1.8023 + 0.0000i

1.7141 - 0.0000i 1.1473 + 0.0000i 1.7446 + 0.0000i

-2.0484 + 0.0000i 1.3874 + 0.0000i 0.5210 - 0.0000i


Matlab graphics

MATLAB Graphics

  • One of the best things about MATLAB is interactive graphics

  • “plot” is the one you will be using most often

  • Many other 3D plotting functions -- plot3, mesh, surfc, etc.

  • Use “help plot” for plotting options

  • To get a new figure, use “figure”

  • logarithmic plots available using semilogx, semilogy and loglog


Plotting commands

Plotting Commands

  • plot(x,y) defaults to a blue line

  • plot(x,y,’ro’) uses red circles

  • plot(x,y,’m*’) uses magenta asterisks

  • If you want to put two plots on the same graph, use “hold on”

  • plot(a,b,’r:’) (red dotted line)

  • hold on

  • plot(a,c,’ko’) (black circles)


Plotting commands1

Plotting Commands

plot (x, y)plot(x1, y1, x2, y2)

plot (x, y, ‘colorsymbolline style’)

» x = linspace(0, 2*pi);

» y = sin (2.*x);

» z = cos (0.5*x);

» plot (x, y)

» plot (x, y, x, z)

» figure (2)

» plot (x, y, 'r o -'); grid on

» hold on

» plot (x, z, 'b * :')

figure or figure (#) : open a figure

(red, circle, solid line)

(blue, star, dotted line)


Graphics commands

Graphics Commands

  • Axis, Labels, and Title

xlabel ( label )ylabel ( label )title ( title of the plot )text (x_location, y_location, text )axis ([ x_min x_max y_min y_max ])

» xlabel (Time)

» ylabel (Temperature)

» title (Temperature Record : 1900 - 2000)

» text (17, 120, Record High )

» text (85, -40, Record Low )

» axis ([0 100 -50 140])» hold off

  - text string


2 d plotting

2-D Plotting

TITLE

LEGEND

TEXT

or

GTEXT

YLABEL

CURVES

XLABEL


2 d plotting1

2-D Plotting

  • x = 0:.1:2*pi;

  • y1 = sin(x);

  • plot(x,y1,'b')

  • grid on

  • hold on

  • y2 = exp(-x);

  • plot(x,y2,'r:*')


Introduction to matlab i

» x=0:0.1:5;

» y=2*x.^3-12*x.^2+8*x-6;

» H=plot(x,y,'b',x,y,'r*');

» set(H,'LineWidth',3,'MarkerSize',12)

» xlabel('x'); ylabel('y');

» title('f(x)=2x^3-12x^2+8x-6');

» print -djpeg075 poly.jpg

Adjust line thickness, font size, marker size, etc.

element-by-element operations x.^n


Introduction to matlab i

» x=0:0.1:10;

» y=sin(2.*pi*x)+cos(pi*x);

» H1=plot(x,y,'m'); set(H1,'LineWidth',3); hold on;

» H2=plot(x,y,'bO'); set(H2,'LineWidth',3,'MarkerSize',10); hold off;

» xlabel('x'); ylabel('y');

» title('y = sin(2\pix)+cos(\pix)');

» print -djpeg075 function.jpg


Introduction to matlab i

» x=0:0.1:3; y1=exp(-x); y2=sqrt(x);

» H=plot(x,y1,'b-',x,y2,'r--');

» set(H,'LineWidth',3)

» xlabel('x'); ylabel('y'); title('MATLAB Plots');

» H1=text(1.8,0.2,'exp(-x)'); set(H1,'FontSize',18);

» H2=text(1.8,1.3,'sqrt(x)'); set(H2,'FontSize',18);


  • Login