Matlab Tutorial

39
Computer Applications --- MATLAB MATLAB (MATrix LABoratory) is a powerful computer language for technical computing that uses arrays (matrices) as basic data elements. It can be used for: mathematical calculations, modeling and simulations, data processing and analysis, visualization and graphics, algorithm and application development, including graphical user interface building as research, development and design software for industry-specific problems Topics: 1. Starting with MATLAB 2. Creating Arrays 3. Mathematical Operations with Arrays 4. Script Files 5. Two-Dimensional Plots 6. Functions and Function Files - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1. STARTING WITH MATLAB MATLAB Windows:

Transcript of Matlab Tutorial

Page 1: Matlab Tutorial

Computer Applications --- MATLABMATLAB (MATrix LABoratory) is a powerful computer language for technical computing that uses arrays (matrices) as basic data elements. It can be used for:

mathematical calculations,

modeling and simulations,

data processing and analysis,

visualization and graphics,

algorithm and application development, including graphical user interface building

as research, development and design software for industry-specific problems

Topics:

1. Starting with MATLAB

2. Creating Arrays

3. Mathematical Operations with Arrays

4. Script Files

5. Two-Dimensional Plots

6. Functions and Function Files

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

1. STARTING WITH MATLABMATLAB Windows:

Window Purpose

Command Window Used to enter variables, commands, and data; runs programs

Figure Window Used to display plots and graphs

Edit Window Creates and debugs script and function files

Help Window Provides help information

Page 2: Matlab Tutorial

Launch Pad Provides access to tools, demos, and documentation

Command History Logs command entered in the command window

Workspace Provides information about the variables that are used

The Command Window is the main window, and can be used for executing commands, opening other windows, running programs written by users, and managing the software.

Notes for working in the Command Window:

To type a command the cursor must be placed next to the command prompt (>>). Press Enter key to execute the command.

Several commands can be typed in the same line by typing a comma between the commands.

If a command is too long to fit in one line, it can be continued to the next line by typing three periods…(called an ellipsis) and pressing the Enter key.

The output of a command is not displayed if a semicolon (;) is typed at the end of a command.

clc command clears the Command Window.

Display FormatsThe default output format for numerical values is fixed-point with 4 decimal digits. The format can be changed with the format command (i.e format short, format long, format bank)Details of these formats can be obtained by typing help format in the Command Window.

DEFINING SCALAR VARIABLESA variable is a name made of a letter or a combination of several letters (and digits) that is assigned a numerical value.

variable_name = a numerical value, or a computable expression

Rules about variable names:

Can be up to 63 characters long.

Can contain letters, digits, and underscore character.

Must begin with a letter

MATLAB is case sensitive.

Page 3: Matlab Tutorial

Avoid using the names of a built-in function for a variable.

Useful Commands for Managing Variables:

Command Outcome

clear Removes all variables from the memory

clear x y z Removes only variables x, y, and z from the memory

who Displays a list of the variable in the memory

whos Displays a more detailed list of the variables currently in the memory.

EXAMPLES OF MATLAB APPLICATIONS

Example 1: A trigonometric identity is given by: cos2

x2=tan x+sin x

2 tan x

Use MATLAB to verify that the identity is correct by calculating each side of the equation, let x = pi/5.

Solution:

>> x = pi/5;

>> LHS = cos(x/2)^2 % left-hand side of the equation

LHS =

0.9045

>> RHS = (tan(x)+sin(x))/(2*tan(x)) %right-hand side of the equation

RHS =

0.9045

Example 2: An object with an initial temperature of To that is placed at time t = 0 inside a chamber that has a constant temperature of Ts, will experience a temperature change according to the equation:Where T is the temperature of the object at a time t, and k is a T=T S+(T 0−T S )e

−kt

Page 4: Matlab Tutorial

constant.

A soda can at a temperature of 120°F (was left in the car) is placed inside a refrigerator where the temperature is 38°F. Determine to the nearest degree, the temperature of the can after three hours. Assume k = 0.45.

First define all the variables and then calculate the temperature using one MATLAB command.

Solution:

>> Ts = 38; T0=120; k=0.45; t = 3;

>> T = round (Ts +(T0 – Ts)*exp(-k*t)) % round is a built-in function that

T =

59

Exercises:Solve the following problems in the Command Window.

1. Define the variables x and z as x = 9.6 and z = 8.1, then evaluate:

a.

xz2=( 2 z3x )35

b.

443 z2x3

+ e− xz

( x+z )

2. In the triangle shown, a = 18 cm, b = 35 cm, and c = 50 cm. Define a, b, and c as variables, and then calculate the angle θ by calculating the variables in the Law of Cosines.

3. Define the following variables:

Table_price = P256.95

c

Answer: 629.1479

Answer: 2.0279

a b

Page 5: Matlab Tutorial

Chair_price = P89.99

Then change the display format to bank and;

a.) evaluate the cost of two tables and eight chairs.

b.) the same as part a.), but add 5.5% taxc.) the same as part b.), but round the total cost to the nearest peso.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

2. CREATING ARRAYS

An array is a list of numbers arranged in rows and/or columns. MATLAB uses arrays to store and manipulate data. Arrays in MATLAB can also be made of a list of characters, which are called strings.

A. Creating a one-dimensional array (vector)a.1 Creating a vector from a known list of numbers:

The vector is created by typing the elements inside square brackets [].

variable_name = [type vector elements]

Row vector: To create a row vector, type the elements with a space or a comma between the elements inside the square brackets.

Column vector: To create a column vector, type the left square bracket [ and then enter the elements with a semicolon between them, or press Enter key after each element. Type the right square bracket ] after the last element. A column vector can be created by the transpose of the row vector. a.2 Creating a vector with constant spacing by specifying first term (m), the spacing (q), and the last term (n).

variable_name = [m:q:n] or variable_name = m:q:n

a.3 Creating a vector with constant spacing by specifying the first and last terms (xi and xf), and the number of terms (n).

variable_name = linspace(xi, xf, n)

B. Creating a two-dimensional array (matrix)

Answer: a.) P1233.82

b.) P1301.68

c.) P1302.00

Page 6: Matlab Tutorial

variable_name = [1st row elements; 2nd row elements; 3rd row

elements;…;last row elements]

Do the following in the Command Window:

1. Create a row vector that has the elements 32, 4, 81, e2.5 , 63, cos(pi/3), and 14.12.

2. Create a column vector in which the element is 15, the elements decreases with increments of -5, and the last element is -25.

3. Create a row vector with 15 equally spaced elements in which the first element is 7 and the last element is 40.

4. Using the ones and zeros command, create a 4 x 5 matrix in which the first two rows are 0’s and the next two rows are 1’s.

5. Create a 6 x 6 matrix in which the middle two rows and middle two columns are 1’s and the rest are 0’s.

Strings and Strings as VariablesA string is an array of characters created by typing the characters within single quotes.Strings can include letters, digits, other symbols, and spaces.It is used in MATLAB in the output commands to display text messages, in formatting commands of plots and as input arguments of some functions.

Example:

>> Name = ‘Juan dela Cruz’

Name =

Juan dela Cruz

MATLAB has a built-in function named char that creates an array with rows that have the same number of characters from an input of rows that are not of the same length.

Variable_name = char(‘string 1’, ‘string 2’, ‘string 3’)

Page 7: Matlab Tutorial

Example:

>> Info = char('Student Name:', 'Juan dela Cruz', 'Grade:', '1.0')

Info =

Student Name:

Juan dela Cruz

Grade:

1.0

Building Structure ArraysYou can build structures in two ways:

Using assignment statements

Using the struct function

Building Structure Arrays Using Assignment Statements

Structures are like cell arrays in that they allow one to group collections of dissimilar data into a single variable. However, instead of addressing elements by number, structure elements are address by names called fields. Structures use dot notation to access data in fields.

Example: Create a data structure variable called circle with fields entitled radius, center, linestyle, and color.

>> circle.radius = 2.5; % semicolon, no display.

>> circle.center = [0,1];

>> circle.linestyle = '--';

>> circle.color = 'red' % no semicolon, so display

circle =

radius: 2.5000

center: [0 1]

linestyle: '--'

color: 'red'

Exercise: Create a data structure my_info with the following fields: name, age, address, civil status, job title, and other data you like to include.

Page 8: Matlab Tutorial

Example:

>> my_info.name = 'Rizza Loquias';

>> my_info.age = '32 years old';

>> my_info.address ='Iriga City';

>> my_info.job_title = 'electronics engineer';

>> my_info

my_info =

name: 'Rizza Loquias'

age: '32 years old'

address: 'Iriga City'

job_title: 'electronics engineer'

Page 9: Matlab Tutorial

3. MATHEMATICAL OPERATIONS WITH ARRAYS

Creation

MATLAB has dozens of functions that create different kinds of matrices. Two of them can be used to create a pair of 3-by-3 example matrices for use throughout this section. The first example is symmetric.

>> A = pascal(3)

A =

1 1 1

1 2 3

1 3 6

The second example is not symmetric.

>> B = magic(3)

B =

8 1 6

3 5 7

4 9 2

Another example is a 3-by-2 rectangular matrix of random integers.

>> C = fix(10*rand(3,2))

C =

9 4

2 8

6 7

A column vector is an m-by-1 matrix, a row vector is a 1-by-n matrix and a scalar is a 1-by-1 matrix. The statements

u = [3; 1; 4]

v = [2 0 -1]

Page 10: Matlab Tutorial

s = 7

produce a column vector, a row vector, and a scalar.

u =

3

1

4

v =

2 0 -1

s =

7

Addition and Subtraction

Addition and subtraction of matrices is defined just as it is for arrays, element-by-element. Adding A to B and then subtracting A from the result recovers B.

>> X = A + B

X =

9 2 7

4 7 10

5 12 8

>> Y = X -A

Y =

8 1 6

3 5 7

4 9 2

Addition and subtraction require both matrices to have the same dimension, or one of them be a scalar. If the dimensions are incompatible, an error results.

>> X = A + C

Error using ==> +

Matrix dimensions must agree.

Page 11: Matlab Tutorial

>> w = v + s

w =

9 7 6

Multiplication of Arrays

>> X = A*B

X =

15 15 15

26 38 26

41 70 39

>> Y = B*A

Y =

15 28 47

15 34 60

15 28 43

Array Division

Two types:

left division \: used to solve the matrix equation AX = B where X and B are column vectors; recommended for solving a set of linear equations.

right division /: used to solve the matrix equation XC = D where X and D are row vectors

Example: Use matrix operation to solve the following system of linear equations.

4x – 2y + 6z = 8

2x + 8y + 2z = 4

6x + 10 y + 3z = 0

Solution:

Page 12: Matlab Tutorial

%Using left division

>> A = [4 -2 6; 2 8 2; 6 10 3];

>> B = [8; 4; 0];

>> X = A\B

X =

-1.8049

0.2927

2.6341

% using inv function

>> A = [4 -2 6; 2 8 2; 6 10 3];

>> B = [8; 4; 0];

>> Xb = inv(A)*B

Xb =

-1.8049

0.2927

2.6341

% using right division

>> C = [4 2 6; -2 8 10; 6 2 3];

>> D = [8 4 0];

>> Xc = D/C

Xc =

-1.8049 0.2927 2.6341

>> Xd = D*inv(C)

Xd =

-1.8049 0.2927 2.6341

>> Xd'

ans =

-1.8049

0.2927

2.6341

The values of x, y, and z are -1.8049, 0.2927, and 2.6341, respectively.

Element-by-element Operations

The operations are carried out on each of the elements of the array.

Symbol Description Symbol Description

.* Multiplication ./ Right division

.^ exponentiation .\ Left division

Element-by-element operations can only be done with arrays of the same size.

Example:

Page 13: Matlab Tutorial

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

A =

1 2 3

4 5 6

1 2 3

>> A.^2

ans =

1 4 9

16 25 36

1 4 9

>> A.*2

ans =

2 4 6

8 10 12

2 4 6

>> A./2

ans =

0.5000 1.0000 1.5000

2.0000 2.5000 3.0000

0.5000 1.0000 1.5000

>> A.\2

ans =

2.0000 1.0000 0.6667

0.5000 0.4000 0.3333

2.0000 1.0000 0.6667

Exercises:

Perform the following in the Command Window:

1. For the function y = (x2 + 1)3x3, calculate the value of y for the following values of x: -2.5 -2 -1.5 -1 -0.5 0 0.5 1 1.5 2 2.5 3. Solve the problem by first creating a vector x, and then creating a vector y, using element-by-element calculations.

2. Define x and y as the vectors x = 2, 4, 6, 8, 10 and y = 3, 6, 9, 12, 15. Then use them in the following expression to calculate z using element-by-element calculations.

3. Solve the following system of four linear equations:

5x + 4y – 2z + 6w = 4

3x + 6y + 6z + 4.5w = 13.5

6x + 12y – 2z + 16w = 20

4x – 2y +2z -4w = 6

Page 14: Matlab Tutorial

4. SCRIPT FILES4.1 NOTES ABOUT SCRIPT FILES

A script file is a sequence of MATLAB commands, also called a program.

When a script file runs, MATLAB execute the commands in the order they are written just as if they were typed in the Command Window.

When a script file has a command that generates an output (e.g. assignment of a value to a variable without semicolon at the end), the output is displayed in the Command Window.

Using script file is convenient because it can be edited (corrected and/or changed) and executed many times.

Script files can be typed and edited in any text editor and then pasted into the MATLAB editor.

4.2 CREATING AND SAVING A SCRIPT FILE

Script files are created and edited in the Editor Window. In the Command window, click File>>New>>m-file.

Save the script file before it can be executed. The rules for naming a script file follow the rules for naming a variable. The names of user-defined variables, predefined variables, MATLAB commands or functions should not be used to name script files.

4.3 RUNNING A SCRIPT FILEA script file ca be executed either by typing its name in the Command Window and then

press Enter, or directly from the Editor window by clicking on the Run icon.

In order to run a file, the file must be in the current directory, or in the search path.

4.3 INPUT INTO A SCRIPT FILE

When a script file is executed the variables that are used in the calculations within the file must have assigned values. The assignment of a value to a variable can be done in three ways:

1. The variable is defined and assigned value in the script file.

2. The variable is defined and assigned value in the Command Window.

Page 15: Matlab Tutorial

3. The variable is defined in the script file, but a specific value is entered in the Command Window when the script file is executed.

There are three ways to obtain input from a user during M-file execution. You can:

Display a prompt and obtain keyboard input.

Pause until the user presses a key.

Build a complete graphical user interface.

Prompting for Keyboard Input

The input function displays a prompt and waits for a user response. Its syntax is

variable_name = input('prompt_string')

The function displays the prompt_string, waits for keyboard input, and then returns the value from the keyboard. If the user inputs an expression, the function evaluates it and returns its value. This function is useful for implementing menu-driven applications.

Example: In the Editor window type the following:

% A simple script file that calculates the average of points scored in

% three games.

game1 = input(‘Enter the points scored in the first game: ’);

game2 = input(‘Enter the points scored in the second game: ’);

game3 = input(‘Enter the points scored in the third game: ’);

average_points = (game1+game2+game3)/3

Save this as ave_score.m, then run in the Command window.

The input command can also be used to assign a string to a variable.

variable_name = input('prompt_string',’s’)

The pause command, with no arguments, stops execution until the user presses a key. To pause for n seconds, use pause(n).

Page 16: Matlab Tutorial

4.4 OUTPUT COMMANDS4.4.1 The disp Command

The disp command is used to display the elements of a variable without displaying the name of the variable, and to display text.

disp(name of a variable) or disp(‘text as a string’)

Example:

% A simple script file that calculates the average of points scored in

% three games.

% The points from each game are assigned to the variables by the user

% The disp command is used to display the output

game1 = input(‘Enter the points scored in the first game: ’);

game2 = input(‘Enter the points scored in the second game: ’);

game3 = input(‘Enter the points scored in the third game: ’);

average_points = (game1+game2+game3)/3;

disp(‘’)

disp(‘The average of points scored in a game is:’)

disp(‘’)

disp(average_points)

4.4.2 The fprintf Command

The fprintf command can be used to display output on the screen or to save it to a file. Unlike with the disp command, the output can be formatted.

fprintf(‘text as a string’)

Using the fprintf command to display a mix of text and numerical data

fprintf(‘text as a string %f additional text’, variable_name)

Example:% A simple script file that calculates the average of points scored in

Page 17: Matlab Tutorial

% three games.

% The points from each game are assigned to the variables by the user

% The fprintf command is used to display the output

game1 = input(‘Enter the points scored in the first game: ’);

game2 = input(‘Enter the points scored in the second game: ’);

game3 = input(‘Enter the points scored in the third game: ’);

average_points = (game1+game2+game3)/3;

fprintf(‘The average of %f points was scored in threegame.’,average_points)

With the fprintf command it is possible to insert more than one number within the text.

fprintf(‘..text..%g..%f..%i..’, variable_name1,variable_name2,variable_name3)

Example:

% this program calculates the distance a projectile flies

%given its initial velocity and angle it is shot.

v = 1584; %initial velocity (km/h)

Theta = 30; % angle in degrees

vms = v*1000/3600; %changing velocity unit to m/s

t = vms*sin(30*pi/180)/9.81; % calculating time to the highest pointd = vms*cos(30*pi/180)*2*t/1000; %calculating max. distance

fprintf(‘A projectile shot at %3.2f degrees with a velocity of %4.2f km/h will travel a distance of %g km.’,theta,v,d)

Another example:

% a simple program that will compute the square roots of numbers given as vector

X = 1:5;

Y = sqrt(x);

T = [x;y]

fprintf(‘If the number is: %i’, its square root is: %f\n’,T)

Page 18: Matlab Tutorial

Example: % A program that will compute a worker’s pay

t=input('Please enter the number of hours worked');

h=input('Please enter the hourly wage in $');

if t>40

Pay=t*h+ (t-40)*0.5*h;

elseif t==40

Pay=t*h+0.75*h;

else

Pay=t*h-(t*0.15*h);

end

fprintf('The worker"s pay is $%5.2f',Pay)

Example: Write a script file that will display the roots of a quadratic equation

Solution:

a = input('enter the value of a >> ');

b = input('enter the value of b >> ');

c = input('enter the value of c >> ');

D = (b^2)-(4*a*c);

x1= (-b +sqrt(D))/(2*a);

x2= (-b -sqrt(D))/(2*a);

if D > 0

fprintf('The equation has two roots.\n')

disp('')

x1

Page 19: Matlab Tutorial

x2

elseif D == 0

fprintf('The equation has one root.\n')

disp('')

x1

x2

else

fprintf('The equation has no real roots.\n')

disp('')

x1

x2

5. Two-Dimensional Plot

5.1 The plot command

This is used to create two-dimensional plots. The basic form is:

plot(x,y)

the arguments x and y are each a vector(one-dimensional array) and can have any name.

Example:

>> x = [1 2 3 5 7 7.5 8 10];

>> y = [2 6.5 7 7 5.5 4 6 8];

>> plot(x,y)

The plot appears on the screen in blue which is the default line color. The plot command has additional optional arguments that can be used to specify the color and style of the line and the color and type of markers, thus the command has the form:

Page 20: Matlab Tutorial

plot(x,y,’line specifiers’,’PropertyName’, PropertyValue)

Line Specifiers:

Line Style Specifier Line Style Specifier

solid (default) - dotted :

dashed -- dash-dot -.

Line Color Specifier Line Color Specifier

red r magenta m

green g yellow y

blue b black k

cyan c white w

Marker Type Specifier Marker Type Specifier

plus sign + square s

circle O diamond d

asterisk * five-pointed star p

point . six-pointed star h

Notes about using the specifiers:

The specifiers are typed inside the plot command as strings. Within the string the specifiers can de typed in any order. The specifiers are optional. This means that none, one, two, or all the three can be

included in a command.

Some examples:

plot(x,y) A blue solid line connects the points with no markers (default).

plot(x,y,’r’) A red solid line connects the points.

plot(x,y,--y’) A yellow dashed line connects the points.

plot(x,y,’*’) The points are marked with * (no line between the points).

Page 21: Matlab Tutorial

plot(x,y,’g:d’) A green dotted line connects the points that are marked with diamond markers.

Property Name and 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:

Property Name

Description Possible Property Values

LineWidth

(or linewidth)

Specifies the width of the line. A number in units of points (default 0.5).

MarkerSize

(or markersize)

Specifies the size of the marker. A number in units of points.

MarkerEdge-Color

(or markeredge-color)

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

Color specifiers from the table above, typed as string.

MarkerFace-Color (or markerface-color)

Specifies the color of the filling for filled markers.

Color specifiers from the table above, typed as a string.

For example, the command:

>> plot (x,y,’-mo’,’LineWidth’,2,’markersize’,12,’MarkerEdgeColor’,’g’,’markerfacecolor’,’y’)

creates a plot that connects the points with a magenta a solid line and circles as markers at the points. The line width is two points and the size of the circle markers is 12 points. The markers have a green edge line and yellow filling.

Page 22: Matlab Tutorial

A note about line specifiers and properties:

The three line specifiers, which are the style and color of the line, and the type of the marker can also be assigned with a PropertyName argument followed by a PropertyValue argument. The Property Names for the line specifiers are:

As with any command, the plot command can be typed in the Command Window, or it can be included in a script file. It also can be used in a function file.

Plot of Given Data

In this case given data is first used to create vectors that are then used in the plot command. Example: the following table contains sales data of a company from 1988 to 1994.

YEAR 1988 1989 1990 1991 1992 1993 1994

SALES (millions)

8 12 20 22 18 24 27

To plot this data, the list of years is assigned to one vector (named yr), and the corresponding sale data is assigned to a second vector (named sle). The Command Window where the vectors are created and the plot is issued shown below:

Specifier Property Name Possible Property Values

Line Style linestyle (or LineStyle)

Line style specifier from the table above, typed as a string.

Line Color color (or Color) Color specifiers from the table above, typed as a string.

Marker marker (or Marker) Marker specifier from the table above, typed as a string.

Page 23: Matlab Tutorial

>> yr = [1988:1:1994];>> sle = [8 12 20 22 18 24 27];>> plot(yr,sle,’—r*’,’linewidth’,2,’markersize’,12)

Line Specifiers: dashed red line and asterisk markerProperty Name and Property Value: the line width is 2 points and the markers size is 12 point

fplot (‘function’,limits,line specifiers)

The domain of x, and optionally, the limits of the y axis.The function to be plotted.

Specifiers that define the type and color of the line and markers (optional).

5.2 The fplot COMMAND

The fplot command plots a function with the form y=f(x) between specified limits. The command has the form:

Example: a plot of the function y = x2 + 4sin(2x) – 1 for -3 ≤ x ≤ 3 can be created by:

>>fplot(‘x^2+4*sin(2*x)-1’,[-3 3])

Page 24: Matlab Tutorial

5.3 Plotting Multiple Graphs in the Same Plot

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 command:

plot(x,y,u,v,t,h)

it is also possible to add line specifiers following each pair. For example the command:

plot(x,y,’-b’,u,v,’—r’,t,h,’g:’)

Example: Plot the function y = 3x2 – 26x + 10, and its first and second derivatives, for – 2 ≤ x ≤ 4, all in the same plot.

Solution:

The first derivative of the function is y’ = 9x2 – 26.

The second derivative is y” = 18x.

A script file that creates a vector x, and calculates the values of y’ and y”, and creates the plot:

x = [-2:0.01:4];

y = 3*x.^3 – 26*x + 6;

yd = 9*x.^2 – 26;

ydd = 18*x;

plot(x,y,’-b’,x,yd,’--r’,x,ydd,’:k’)

5.4 Formatting a Plot Using Commands

The xlabel and ylabel commands:

Page 25: Matlab Tutorial

xlabel (‘text as string’)

ylabel (‘text as string’)

The title command:

title (‘text as string’)

The text command:

text (x,y,’text as string’)

gtext (‘text as string’)

The legend command:

legend (‘string1’,’string2’, ...... , pos)

where pos is an optional number where in the figure the legend is placed (-1,0,1,2,3,and 4)

Formatting the text in the xlabel, ylabel, title, text, and legend commands:

Modifier Effect

\bf Bold font

\it Italic effect

\rm Normal font

\fontname {fontname} Specified font is used

\font size {specified font size is used}

Greek Characters:

Characters in the string Greek Letter

Page 26: Matlab Tutorial

\alpha α

\beta β

\gamma γ

\theta θ

\pi π

\sigma σ

\Phi Ф

\Delta Δ

\Gamma Γ

\Lambda Λ

\Omega Ώ

\Sigma Σ

Formatting of the text that is displayed has the form:

text (x,y, ‘text as string’ ,PropertyName, Property Value)

Property Name Description Possible Property Values

Rotation Specifies the orientation of the text

Scalar (degrees)

Default: 0

Font angle Specifies italic or normal style characters

Normal, italic

Default: normal

Font name Specifies the font for the text

Font name that is available in the system

Font size Specifies the size of the font

Scalar (points)

Default: 10

Font weight Specifies the weight of Light, normal, bold

Page 27: Matlab Tutorial

the characters

Default: normal

Color Specifies the color of the text

Color specifiers (see section 5.1).

Background color Specifies the background color

Color specifiers (see section 5.1)

Edgecolor Specifies the the color of the edge of a rectangular box

Color specifiers (see section 5.1) default: none

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

Scalar (points)

Default: 0.5

The axis command

axis ( [xmin, xmax]) sets the limits of the x axis (xmin and xmax are numbers).

axis ([xmin,xmax,ymin,ymax]) sets the limits of the x and y axes.

axis equal sets the same scale for both axes

axis square sets the axis region to be square.

The grid command:

grid on Adds grid lines to the plot.

grid off Removes the grid line from the plot

Example:

%a script file that will generate a formatted plot

x = [10:0.1:22];

y = 95000./x.^2;

Page 28: Matlab Tutorial

xd= [10:2:22];

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

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

xlabel(‘DISTANCE (cm)’)

ylabel(‘INTENSITY (lux)’)

title(’\fontname{Arial}Light Intensity as a Function ofDistance’,’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.0,’markersize’,10)

legend(‘Theory’,’Experiment’,0)

hold off

5.5 PLOTS WITH LOGARITHMIC AXES

MATLAB commands for making plots with log axes are:

semilogy (x,y) plots y versus x with a log (base 10) scale for the y and axis and linear scale for the x axis

semilogx (x,y) plots y versus x with a log (base 10) scale for the x axis and linear scale for the y axis

loglog (x,y) plots y versus x with a log scale for both axes

Example:

Type in the Command window and observe the generated plots for the same function:

>> linspace(0.1,60,1000);

>> y = 2.^(-0.2*x+10);

>> plot(x,y)

Page 29: Matlab Tutorial

>> linspace(0.1,60,1000);

>> y = 2.^(-0.2*x+10);

>> semilogy(x,y)

>> linspace(0.1,60,1000);

>> y = 2.^(-0.2*x+10);

>> semilogx(x,y)

>> linspace(0.1,60,1000);

>> y = 2.^(-0.2*x+10);

>> loglog(x,y)

Notes for plots with logarithmic axes:

The number zero cannot be plotted on a log scale (since log zero is not defined) Negative numbers cannot be plotted on a log scales (since a log of a negative

number is not defined)

5.7 HISTOGRAMS

hist (y)

y is with the data points. MATLAB divides the range of the data points into 10 equally spaced subranges (bins), and then plots the number of data points in each bin.

hist (y, nbins) or hist (x,y)

nbins is a scalar that defines the number of bins. MATLAB divides the range to equally spaced sub-ranges.

x is a vector that specifies the location of the center of each bin (the distance between the centers does not have to be the same for all the bins). The edges of the bins are at the middle point between the centers.

Page 30: Matlab Tutorial

Function FileData input Output

5.8 POLAR PLOTS

polar (theta,radius,line,’specifiers’)

Example 1:

%% plotting a flower%theta=linspace(0,2*pi,200);r=3*cos(3*theta);polar(theta,r)title('Three leaved Rose or Trefoil')

6. Function and Function Files

STRUCTURE A FUNCTION FILE

(Optional) specifiers that define the type and color of the line and markers.

Vector

Page 31: Matlab Tutorial

A function definition line. This line defines the function name, and the number and order of input and output arguments.

An H1 line. H1 stands for "help 1" line. MATLAB displays the H1 line for a function when you use look for or request help on an entire directory.

Help text. MATLAB displays the help text entry together with the H1 line when you request help on a specific function.

The function body. This part of the function contains code that performs the actual computations and assigns values to any output arguments.

FUNCTION DEFINITION LINE

Defines the file as a function Defines the name of the function Defines the number and order of the input and output arguments.

The form of the function definition line is:

function [output arguments] = function_name (input arguments)

Input and Output Arguments

Function definition line Comments

function[mpay,tpay] = loan(amount,rate,years) Three input arguments, two output Arguments

function [A] = RectArea(a,b) Two input arguments, one output argument

function A = RectArea[a,b] Same as above, one output argument can be typed without the brackets.

function [V,S] = SphereVolArea(r) One input variable, two output variables.

function trajectory(v,h,g) Three input arguments, no output arguments

The word function must be the first word, and must be typed in lower-case letters.

A list of output arguments typed inside brackets

The name of the function

A list of input arguments typed inside parentheses.

Page 32: Matlab Tutorial

SAVING A FUNCTION FILE

function definition line File name

function[mpay,tpay] = loan(amount,rate,years) loan.m

function[A] RectArea(a,b) RectArea.m

function[V,S] = SphereVolArea(r) SphereVolArea.m

function trajectory(v,h,g) trajectory.m

EXAMPLE OF SIMPLE FUNCTION FILES

1. loan.m

function [mpay, tpay] = loan(amount,rate,years)

%loan calculates monthly and total payment of loan.

%Input arguments:amount=loan in $.

%rate=annual interest rate in percent.

%years=number of years.

%Output argument:

%mpay=mothly payment, tpay=total payment.

Page 33: Matlab Tutorial

format bank

ratem=rate*0.01/12;

a=1+ratem;

b=(a^(years*12)-1)/ratem;

mpay=amount*a^(years*12)/(a*b);

tpay=mpay*years*12;

2. CartesianToPolar.m

function [theta, radius] = CartesianToPolar (x,y)

% a function that determines the polar coordinates of a point from the

% Cartesian coordinates in a two-dimensional plane.

% input arguments are the x and y coordinates of the point

% output arguments are the angle theta (in degrees) and the radial distance

% to the point

theta = atan(y/x)*(180/pi); % computes for the angle

radius = sqrt((x^2)+(y^2)); % computes for the radial distance

if (x > 0) & (y > 0)

theta

radius

elseif (x < 0) & (y > 0)

theta

radius

elseif (x < 0) & (y < 0)

theta

radius

else

theta*(-1)

Page 34: Matlab Tutorial

radius

end

COMPARISON BETWEEN SCRIPT FILES AND FUNCTION FILES

Both script and function files are saved with the extension .m (that is why they are sometimes called M-files)

The first line in function file is the function definition line. The variable in the function file are local. The variables in a script file are

recognized in the Command Window. Script files can use variables that have been defined in the workspace. Script file contains sequence of MATLAB commands (statements). Function files can accept data through input arguments and can return data

through output arguments. When a function file is saved, the name of the file should be the same as the name

of the function.