mathlab activity

20
INTODUCTION TO MATLAB INTRODUCTION TO MATLAB WHAT IS MATLAB? MATLAB is an interactive package for numerical analysis, matrix computation, control system design and linear system analysis and design. The name MATLAB stands for matrix laboratory. MATLAB is a high performance language for technical computing. It integrates computation, visualization, and programming in an easy to use environment where problems and solutions are expressed in familiar mathematical notation. Typical uses include: Math and computation Algorithm development Modeling, simulation and prototyping Data analysis, exploration and visualization Scientific and engineering graphics Application development, including graphical user interface building WORKING IN MATLAB: While working with MATLAB you get on your screen always a prompt. This is >>. This means that MATLAB is ready to accept commands. If you press the enter key, the commands get executed. Unless you finish your command with a semicolon (;), MATLAB displays the result on screen. With clear you de-allocate memory space for those variables. If you want to use some or all of the variables with their values in a later MATLAB session you can save the workspace variables with the command save FILENAME which creates the binary MAT-file named FILENAME.mat. With load FILENAME, the workspace variables are loaded from the file FILENAME.mat. MATLAB records the commands you typed in. you can scroll through the list of executed commands with the arrow keys and The arrows and enable to go the location in the command where edits are necessary. This is convenient to correct type errors in a command, or if you need to execute lots of slightly different versions of the same instruction.

Upload: muhammad-saad

Post on 12-May-2017

232 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: mathlab activity

INTODUCTION TO MATLABINTRODUCTION TO MATLAB

WHAT IS MATLAB?MATLAB is an interactive package for numerical analysis, matrix computation, control system design and linear system analysis and design. The name MATLAB stands for matrix laboratory. MATLAB is a high performance language for technical computing. It integrates computation, visualization, and programming in an easy to use environment where problems and solutions are expressed in familiar mathematical notation. Typical uses include:

Math and computation Algorithm development Modeling, simulation and prototyping Data analysis, exploration and visualization Scientific and engineering graphics Application development, including graphical user interface building

WORKING IN MATLAB:

While working with MATLAB you get on your screen always a prompt. This is >>. This means that MATLAB is ready to accept commands. If you press the enter key, the commands get executed. Unless you finish your command with a semicolon (;), MATLAB displays the result on screen.

With clear you de-allocate memory space for those variables. If you want to use some or all of the variables with their values in a later

MATLAB session you can save the workspace variables with the command save FILENAME which creates the binary MAT-file named FILENAME.mat.

With load FILENAME, the workspace variables are loaded from the file FILENAME.mat.

MATLAB records the commands you typed in. you can scroll through the list ofexecuted commands with the arrow keys and

The arrows and enable to go the location in the command where edits are necessary. This is convenient to correct type errors in a command, or if you need to execute lots of slightly different versions of the same instruction.

Page 2: mathlab activity

MATLAB SCREEN:Invoke MATLAB like any WINDOWS program. A text oriented command window will pop up, initially looking like picture below:

For any other view, it can be changed to the above one, with the help of following icon:

The above is the MATLAB screen which you see on your desktop –it is broken into 3 parts:

Page 3: mathlab activity

On the right you have the Command Window – this is where you type commands and usually the answers (or error messages) appear here too.

On the top left you have the Workspace window – if you define new quantities (called variables) there names should be listed here.

On the bottom left you have Command History window – this is where past commands are remembered. If you want to re-run a previous command or to edit it you can drag it from this window to the command window to re-run it.

1- GETTING STARTED WITH MATLAB:

SCALARS/CONSTANTSMATLAB considers a single declared element as a scalar quantity or more precisely 1X1 matrix. A scalar can be a real or complex number. For example, enter the following commands in command window:>> x=3>> y=6+4i>> z=7;

What is the difference between command: 1 and command: 3? What is the function of “;”? Explain.

OPERATION WITH SCALARS:

You can perform basic math functions with scalars. Try the following commands and note the results:>>x+z

>>x-y

>> x*z

>> x/z

>> 1.23e 5

>> (x+z)*(z-x)

Page 4: mathlab activity

>>(x+z)^2/(2+x)

ASSIGNMENT STATEMENTSNew variables can be created by using existing variables. Try the following examples:>> u=x*z

>> v=z/x

>> w=x^z

BUILT-IN VARIABLES AND FUNCTIONSSome built-in variables and functions are defined in MATLAB as shown below:>> pi

>> cos (pi)

>> sqrt(x)

>> exp(z)

>> ln(4)

>> log(4)

>>log10(4)

>> 1/0

>>1/Inf

Page 5: mathlab activity

MATLAB works to 15 significant figures but by default shows only 5 figures. Type pi and you will normally get 3.1416. You can change the format to long in which all 15 figures are displayed. >> format long>> pi

Try the following commands too, and note down the result>> formab short pi>>pi

>> format rat>> pi

Type the following command, and explore the concept of “format”>> help format

VARIABLE NAMES MATLAB distinguishes between lower case and capital letters – so A and a are

different objects fro MATLAB. This means that A and a will be treated as separate variables and we can store different values in them quite easily and safely.

Only first 19 characters in a variable name are important. They must begin with a letter character, e.g.

o Acceptable names: A2, x1, ydot, velocity, rel_currento Un-acceptable: 2D, +-, tank volume, #2

Try entering the following two examples and note the MATLAB error:>> wall height = 30>> @x = 9

2- MATRICES

ENTERING ROW MATRICESTo create a row matrix, we may use two methods:

Manually entering the values Creating the row vector by incremental operator

For example, enter the following commands in the command window and note down the responses:>> a = [1 2 3 4 5 6 7]

Page 6: mathlab activity

>> t = 0:10

>> p = 0:0.5:5

What is the difference between command 2 and 3? What has actually made the difference?

Manipulating vectors is as easy as creating them. For example, we can make following “addition” operations;

>> b = a+2;

>> c = a+b;

Subtraction of vectors of the same length works exactly the same way.

ENTERING COLUMN MATRICESColumn vectors are like the ones that appear on the RHS of a set – e.g.

2

0

1

5

The above is a matrix with just one column. The example above has 3 rows.

To create above column matrix in MATLAB, we have 3 methods, Manually entering the values Using transpose Using semi-colon operator

For example, the following three commands will yield the same result:>> g =[2 0 -1 5]>> h = [ 2 0 -1 5]’>> i = [2; 0; -1; 5]

Page 7: mathlab activity

The semi-colons in last command are essential otherwise the statement would return a row matrix.

(mxn) MATRICESThere are two different ways to enter a matrix in MATLAB:>> p =[ 10 2 33

0 1 -21 5 9]

>> q =[0 2 9; 6 5 3; 0 9 1]

Enter a 2X3 matrix and 3X2 matrix with different methods:

MATRIX ADDITION AND SUBTRACTIONMatrix dimensions must be same for these two operations:>> a = [1 2 3]>> b = [1; 4; 6]>> c = a+b

What is the MATLAB response?

MATRIX MULTIPLICATIONThe “inner” dimensions of matrix must be same, i.e. (m x n) matrix * (n x m) matrix.>>m = [1 2; 5 2; 7 0];>>n = [6 5 4; 1 9 7; 2 8 3; 0 2 3];>>l = m * n;

What is the MATLAB response?

>> l = n * m;

Page 8: mathlab activity

What is the MATLAB response?

Note that the product of an (n x m) matrix and an (m x n) matrix yields an (n x n) matrix (i.e. the inner dimensions “cancel each other out”)

TERM BY TERM MATRIX OPERATIONSYou can multiply and divide matrices on a term-by-term basis. This is done by placing a period before the operator.For example, enter the following commands and note the result:>> m .*m ;

>> m .^2;

Note that when we have to perform term by term operations on matrices, they must have the same dimensions as we specify in the addition and subtraction operation for matrices.>> n .*m ;

Why the above operation has not been implemented?

MATRIX TRANSPOSEThis interchanges the rows and columns of a matrix. This converts an (m x n) matrix into an (n x m) matrix.>> m = [0 7; 2 3; 3 8; 5 4];>> r=m’

Note down the MATLAB response:

Page 9: mathlab activity

MATRIX DETERMINANTYou can enter a matrix and find out its determinant in the following way:>> m = [1 1 3; 4 5 6; 9 4 8];>> n = det(m)

MATRIX INVERSEEnter a new matrix and determine its inverse:>>r = [1 5 9; 3 2 0; -3 5 2];

>>p = inv(r)

Enter a new matrix Z, and compute its inverse:>> z = [1 2 3; 4 5 6; 7 8 9];>> y = inv(z)

The MATLAB response in this case will be:

Warning: Matrix is close to singular or badly scaled. Results may be inaccurate. RCOND = 1.541976e-018.

ans =

1.0e+016 *

-0.4504 0.9007 -0.4504 0.9007 -1.8014 0.9007 -0.4504 0.9007 -0.4504

The above response is due to the fact that the matrix: z is a singular one. You can verify this by determining its determinant.>> x = det(z)

We know that if the determinant of a matrix is zero, then it is not invertible.

MATRIX DIVISIONMATLAB has several options for matrix division. You can “right divide” and “left divide”.>>k = [1 7 0; 0 4 -1; 8 3 5];>>n=[5 4 3; 9 8 7; 1 2 3];>>k/n

Page 10: mathlab activity

This is equivalent to the MATLAB expression:>> k * inv(n)

For left division, use the “backslash character”>>k\n

This is equivalent to the MATLAB expression:>> inv(n) * k

SIZE OF MATRIXThe size of a matrix is determined by the command size(). For example, try the following commands,>>a =[1 2 3; 4 5 6];>>size(a)

Similarly, to have the no. of elements in vector, we use the command length().>> b = [1 2 3 4];>> length(b)

Enter 3 matrices, all with different orders, and use the command length() on them. By looking at the answer, can you guess what does it return?

INDEXING ARRAYS AND MATRICESIt deals with singling out particular elements of a vector or matrix:In vectors, for example,>> a = [1 3 5 9];>>a(3)

In a matrix, for example, we want to refer the element of row 2, column 3:>> a = [2 9 4; 3 1 7; 2 0 5];>>a(2,3)

Page 11: mathlab activity

SHORT-CUTS FOR CREATING SPECIAL MATRICESTo enter a matrix of all zeros, we have the command:>> z1= zeros(3,3)

>> z2 = ones(4)

>> I = eye(4)

REFERENCING PARTS OF ARRAYS AND MATRICESThe colon operator is used to specify the range. For example, consider the following array and look at the method of extracting its few elements:>> a = [1 3 4 6 9 4 7];>> b = a(1:3)

Similarly, in a matrix, we want to put rows 1 and 2 & columns 2 and 3 of matrix n into a new matrix m. Type:>> n = [1 2 3; 4 5 6; 7 8 9];>> m = n(1:2, 2:3)

Type the following commands. Along with the response, also note down your comment that what the command has actually done:>> c = n(:,1)

>> r = n(2, :)

Page 12: mathlab activity

Write down the command which will extract all the rows and column 1 and 3 of matrix: n. Save it into the matrix: k

TWO-DIMENSIONAL PLOTS

PLOTTING:

MATLAB is very useful for making scientific and engineering plots. You can create plots of known, analytical function and date from other sources such as experimental measurements. You can analyze data, perhaps by fitting it to a curve and then plot the comparison. MATLAB also has powerful built-in routines for drawing contour and three dimensional surface plots.

1- THE plot() COMMAND:

Two dimensional line and symbol plots are created with the plot command. In its simple form, plot takes two arguments. >> plot(xdata, ydata)

Where xdata and ydata are vectors containing the data. Note that xdata and ydata must be of the same length and both must be of the same type, i.e. both must be either row or column vectors. Let we test the above command on two equal sized row vectors,>> x = [1 2 3 4 5 7 7.5 8 10];>> y = [2 6.5 7 7 5.5 4 6 8];>> plot(x, y)

What is the default color and style of the plot?

The plot() command has additional optional arguments that can be used to specify the color and style of the line and the color and style of markers, if any are desired. With these options, the command has the form>> plot(x, y, ‘line specifiers’, ‘property name’, ‘property value’)

LINE SPECIFIERS: Line specifiers are optional and can be used to define the style and color of the line and the type of markers (if markers are desired). The line style specifiers are:

Line style Specifier Solid (default) -

dashed --dotted :

Dash-dot -.

Page 13: mathlab activity

The line color specifiers are:

Line color Specifier red r

green gblue bcyan c

magenta myellow yblack kwhite w

The marker type specifiers are:

Marker type Specifier Plus sign +

circle oasterisk *point .

square sdiamond d

Five-pointed star pSix-pointed star h

The specifiers are typed inside the plot() command as stringsWithin the string, they can be typed in any order. The specifiers are optional. This means that none, one, two or all three of them can be included in the command.

For example, try the following commands:>> plot(x, y)>> plot(x, y, ‘r’)>> plot(x, y, ‘--g’)>> plot(x, y, ‘*’)>> plot(x, y, ‘g:d’)

PROPERTY NAME & PROPERTY VALUE:Properties are optional and can be used to specify the thickness of the line, the size of the marker, and the colors of the marker’s edge line and fill. The property name is typed as a string followed by a comma and a value for the property, all inside the plot() command.Four properties and possible values are:

Page 14: mathlab activity

Property name DescriptionPossible

property values

linewidthSpecifies the width of the line

A number in units of points (default 0.5)

markersize Specifies the size of the marker

A number in units of points

markeredgecolor

Specifies the color of the marker, or the color of the edge line for filled markers

Color specifiers from the table already given, typed as string

markerfacecolorSpecifies the color of the filling for filled marker

Color specifiers from the table already given, typed as string

For example, try the command,>> plot(x, y, ‘-.mo’, ‘linewidth’, 2, ‘markersize’, 12, ‘markeredgecolor’, ‘g’, ‘markerfacecolor’, ‘y’)

A NOTE ABOUT LINE SPECIFIERS AND PROPERTIES:The three line specifiers, which are style and color of the line, and the type of the marker, can also be assigned with a property name argument followed by a property value argument. The property names for the line specifiers are:

Specifier Property namePossible property

values

Line style linestyleLine style specifier from the table

Page 15: mathlab activity

already given, typed as string

Line color color

Color specifiers from the table already given, type as string

Marker marker

Marker specifeirfrom the table already given, typed as string

2- PLOT OF A GIVEN DATA:In this case, the given data is first used to create vectors that are then used in the plot() command. For example, the following table contains sales data of a company (in millions) from 1988 to 1994

Year 1988 1989 1990 1991 1992 1993 1994Sales 8 12 20 22 18 24 27

To plot the data, use the following commands:>> year = 1988:1994;>> sale = [8 12 20 22 18 24 27];>> plot(year, sale, ‘--r*’, ‘linewidth’, 2, ‘markersize’ ,12)

3- PLOT OF A FUNCTION:In order to plot a function y = f(x), with the plot() command, the user needs to first create a vector of values of x for the domain that the function will be plotted. Then, a vector y is created with the corresponding values of f(x) by using element-by-element calculation (the dot operator). As an example, let we plot the function:

0.5( ) 3.5 cos(6 ) for 2 4xf x y x x Enter the following commands in command window:>> x = -2:0.01:4;>> y = 3.5.^(-0.5*x).*cos(6*x);>> plot(x, y)

Page 16: mathlab activity

4- THE fplot() COMMAND:The fplot() command plots a function with the form y = f(x) between specified limits. The command has the form:>> fplot(‘function’, limits, line specifiers)

For example, for the above function, type the command>> fplot(‘3.5.^(-0.5*x).*cos(6*x)’, [-2, 4], ‘:ro’)

Page 17: mathlab activity

5- PLOTTING MULTIPLE PLOTS IN THE SAME WINDOW:There are three methods to plot multiple plots in the same window:

USING THE plot() COMMAND:Two or more graphs can be created in the same plot by typing pairs of vectors inside the plot() command. The format of the command is:>> plot(x, y, u, v, t, h)

It creates three plots y vs. x, v vs. u and h vs. t, all in the same plot. The vectors of eachpair must be of the same length. MATLAB automatically plots the graphs in different colors so that they can be identified. It is also possible to add line specifiers following each pair. For example, note the format:>> plot(x, y, ‘--b’, u, v, ‘--r’, t, h, ‘:g’)

Lets plot a function y = 3x3 - 26x + 10, and its first and second derivatives, -2 ≤ x ≤ 4, all in the same plot. We will enter the following commands:>> x = -2:0.01:4;>> y = 3*x.^3 – 26*x + 10;>> yd = 9*x.^2 -26;>> ydd = 18*x;>> plot(x, y, ‘:r’, x, yd, ‘.-k’, x, ydd, ‘-g’)

USING THE hold on/off COMMANDS:For using hold on/off commands, we first have to use the usual plot() command. Then the hold on command is typed. Additional graphs can be added with the plot() command that are typed next. Each plot() command creates a graph that is added to that figure. The hold off command then stops this process.For example, a solution of previous problem is shown below with the hold on/off commands:>> x = -2:0.01:4;>> y = 3*x.^3 – 26*x + 10;>> yd = 9*x.^2 -26;>> ydd = 18*x;>> plot(x, y, ‘:r’)>> hold on>> plot(x, yd, ‘.-k’)>> plot(x, ydd, ‘-g’)>> hold off

USING THE line() COMMAND:With the line() command, additional graphs (lines) can be added to a plot that already exists. The format of the line command is:>> line( x, y, ‘property name’, ‘property value’)

Page 18: mathlab activity

The line command does not have the line specifiers, but the line style, color, and marker can be specified with the property name and property value features. For example, note the command:>> line(x, y, ‘linestyle’, ‘--‘, ‘color’, ‘r’, ‘marker’, ‘o’)

The major difference between the plot() and line() commands is that the plot() command starts a new plot every time it is executed, while the line() command adds lines to a plot that already exists. To make a plot that has several plots, a plot() command is typed first and then line() commands are typed for additional graphs.

The same problem (y and its first and second derivative) can be shown with the line commands as follows:>> x = -2:0.01:4;>> y = 3*x.^3 – 26*x + 10;>> yd = 9*x.^2 -26;>> ydd = 18*x;>> plot(x, y, ‘linestyle’, ‘:‘, ‘color’, ‘r’)>> line(x, yd, ‘linestyle’, ‘.-, ‘color’, ‘k’)>> line(x, ydd, ‘linestyle’, ‘-‘, ‘color’, ‘g’)

6- FORMATTING A PLOT:The plot() and fplot() commands create bare plots. The plots can be formatted by using MATLAB commands that follow these commands. Formatting can also be done in the figure window with the plot editor after a plot has been created holds only for the specific plot, and will have to be repeated the next time the plot is created.

THE xlabel() AND ylabel() COMMANDS:Labels can be placed next to the axes with the xlabel() and ylabel() commands which have the format:>> xlabel(‘text as string’)>> ylabel(‘text as string’)

THE title() COMMAND:A title can be added to the plot with the command:>> title(‘text as string’)

THE text() COMMAND:A text label can be placed in the plot with the text() or gtext() commands.>> text(x, y, ‘text as string’)>> gtext(‘text as string’)

The text() command places the text in the figure such that the first character is positioned at the point with the co-ordinates x and y. the gtext() command places the text at a position as specified by the user.

Page 19: mathlab activity

Formatting of the text that is displayed by the xlabel(), ylabel(), title(), text() and gtext() commands can also be done by adding optional property name and property value arguments following the string inside the command. With this option, the text() command, for example, becomes:>> text(x, y, ‘text as string’, ‘property name’, ‘property value’)

Some of the property names and property values are:

Property name description Possible property values

rotationSpecifies the orientation of the text

Scalar(degree)Default: 0

fontangleSpecifies italic or normal style values

Normal, italicDefault: normal

fontnameSpecifies the font for the text

Font name that is available in the system

fontsizeSpecifies the font for the text

Scalar (points)Default: 10

fontweight Specifies the weight for the characters

Light, normal, boldDefault: normal

colorSpecifies the color for the characters

Color specifiers from the table already given

backgroundcolorSpecifies the background color (rectangular area)

Color specifiers from the table already given

edgecolor

Specifies the color of the edge of the rectangular box around the text

Color specifiers from the table already given

linewidth

Specifies the width of the edge of the rectangular box around the text

Scalar (points)Default: 0.5

THE legend() COMMAND:The legend() command places a legend on the plot. The legend shows a sample of the line type of each graph that is plotted and places a label, specified by the user, beside the line sample. The format of the command is:>> legend(‘string1’, ‘string2’, ‘string3’, ……)

The strings are the labels that are placed next to the line sample. Their order corresponds to the order that the graphs were created.

Page 20: mathlab activity

THE axis() COMMAND:When the plot() command is executed, MATLAB creates axes with limits that are based on the minimum and maximum values of the elements of x and y. The axis() command can be used to change the range and the appearance of the axes. In many situations, a graph looks better if the range of the axes extend beyond the range of the data. The following is the format of axis command:>> axis([xmin, xmax, ymin, ymax])An example of formatting a plot by using commands is given below:>> 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)>> xlabel(‘Distance(cm)’)>> ylabel(‘Intensity(lux)’)>> title(‘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)>> hold on>> plot(xd, yd, ‘ro--‘, ‘linewidth’, 1, ‘markersize’, 10)>> legend(‘theory’, ‘experiment’)>> hold off