Matlab Tutorial
Matlab Tutorial
MATLAB (MATrix LABoratory) is a powerful computer language for technical computing that uses arrays (matrices) as basic data elements. It can be used for:
y y y y y y
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 -----------------------------------------------------------
Provides help information Provides access to tools, demos, and documentation Logs command entered in the command window 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.
Display Formats The 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 VARIABLES A variable is a name made of a letter or a combination of several letters (and digits) that is assigned a numerical value.
y y y
Can be up to 63 characters long. Can contain letters, digits, and underscore character. Must begin with a letter
y y
MATLAB is case sensitive. Avoid using the names of a built-in function for a variable.
Command
Outcome Removes all variables from the memory Removes only variables x, y, and z from the memory Displays a list of the variable in the memory Displays a more detailed list of the variables currently in the memory.
cos 2
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 = 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
T ! TS (T0 TS )e kt
to the equation: Where T is the temperature of the object at a time t, and k is a constant. A soda can at a temperature of 120F (was left in the car) is placed inside a refrigerator where the temperature is 38F. 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.
2z xz 2 ! 3x
3 5
Answer: 629.1479
b.
e xz 443 z 2 x 3 ( x z)
Answer: 2.0279
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 Chair_price = P89.99 Answer: a.) P1233.82 b.) P1301.68 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% tax c.) the same as part b.), but round the total cost to the nearest peso. -----------------------------------------------------------c.) P1302.00
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 [].
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 = [1st row elements; 2nd row elements; 3rd row elements;;last row elements]
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 0s and the next two rows are 1s.
5. Create a 6 x 6 matrix in which the middle two rows and middle two columns are 1s and the rest are 0s.
Strings and Strings as Variables A 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:
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) Example: >> Info = char('Student Name:', 'Juan dela Cruz', 'Grade:', '1.0') Info = Student Name: Juan dela Cruz Grade: 1.0 Building Structure Arrays You can build structures in two ways:
y y
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.
% semicolon, no display.
% no semicolon, so display
center:
[0 1]
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. 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'
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]
s = 7 produce a column vector, a row vector, and a scalar. u = 3 1 4 v = 2 s = 7 Addition and Subtraction Addition and subtraction of matrices is defined just as it is for arrays, elementby-element. Adding A to B and then subtracting A from the result recovers B. >> X = A + B X = 9 4 5 2 7 12 7 10 8 0 -1
>> Y = X -A Y = 8 3 4 1 5 9 6 7 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.
>> w = v + s w = 9 7 6
Multiplication of Arrays
>> X = A*B X = 15 26 41 15 38 70 15 26 39
>> Y = B*A Y = 15 15 15 28 34 28 47 60 43
Array Division Two types: y 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:
%Using left division % using right 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
>> 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
>> 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
Element-by-element Operations The operations are carried out on each of the elements of the array. Symbol .* .^ Description Multiplication exponentiation Symbol ./ .\ Description Right division Left division
Element-by-element operations can only be done with arrays of the same size.
Example: >> A = [1 2 3;4 5 6;1 2 3] A = 1 4 1 >> A.^2 ans = 1 16 1 4 25 4 9 36 9 2 5 2 3 6 3 >> A.*2 ans = 2 8 2 >> A./2 ans = 0.5000 2.0000 0.5000 >> A.\2 ans = 2.0000 0.5000 2.0000 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. 1.0000 0.4000 1.0000 0.6667 0.3333 0.6667 1.0000 2.5000 1.0000 1.5000 3.0000 1.5000 4 10 4 6 12 6
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
4. SCRIPT FILES
4.1 NOTES ABOUT SCRIPT FILES y 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.
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 FILE A 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.
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: y y y 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
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).
4.4 OUTPUT COMMANDS 4.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.
or
disp(text as a string)
% 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 % 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; Theta = 30; vms = v*1000/3600; t = vms*sin(30*pi/180)/9.81; d = vms*cos(30*pi/180)*2*t/1000; %initial velocity (km/h) % angle in degrees %changing velocity unit to m/s % calculating time to the highest point %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)
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 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:
plot(x,y,line specifiers,PropertyName, PropertyValue) Line Specifiers: Line Style solid (default) dashed Line Color red green blue cyan Marker Type plus sign circle asterisk point Specifier Line Style dotted dash-dot Line Color magenta yellow black white Marker Type square diamond five-pointed star six-pointed star Specifier
-Specifier
: -.
Specifier
r g b c
Specifier
m y k w
Specifier
+ O * .
s d p h
Notes about using the specifiers: y y y 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) plot(x,y,r) plot(x,y,--y) plot(x,y,*) A blue solid line connects the points with no markers (default). A red solid line connects the points. A yellow dashed line connects the points. The points are marked with * (no line between the points).
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 markers 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.
Property Name LineWidth (or linewidth) MarkerSize (or markersize) MarkerEdgeColor (or markeredgecolor)
Specifies marker.
the
size
of
Specifies the color of the Color specifiers from the marker, or the color of the edge table above, typed as string. line for filled markers.
MarkerFaceSpecifies the color of the filling Color (or for filled markers. markerfacecolor) For example, the command:
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.
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:
Specifier
Property Name
Line Style
(or Line style specifier from the table above, typed as a string. Color specifiers from the table above, typed as a string. Marker specifier from the table above, typed as a string.
Line Color
Marker
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.
1988
1989
1990
1991
1992
1993
1994
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: >> 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 marker Property Name and Property Value: the line width is 2 points and the markers size is 12 point
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: fplot (function,limits,line specifiers)
Specifiers that define the type and color of the line and markers (optional).
>>fplot(x^2+4*sin(2*x)-1,[-3 3])
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;
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 \bf Effect Bold font
Italic effect Normal font Specified font is used {specified font size is used}
Greek Characters:
Characters in the string \alpha \beta \gamma \theta \pi \sigma \Phi \Delta \Gamma \Lambda \Omega \Sigma
Greek Letter
Description
Default: 0
Specifies italic or normal Normal, italic style characters Default: normal Specifies the text the font for Font name that is available in the system
Font name
Font size
Specifies the size of the Scalar (points) font Default: 10 Specifies the weight of Light, normal, bold the characters Default: normal Specifies the text the color of Color specifiers section 5.1). the Color specifiers section 5.1) (see
Font weight
Color
Background color
(see
Edgecolor
Specifies the the color Color specifiers (see of the edge of a section 5.1) default: rectangular box none Specifies the width of Scalar (points) the edge of the Default: 0.5 rectangular box around the text.
Linewidth
sets the limits of the x axis (xmin and xmax are numbers). sets the limits of the x and y axes.
sets the same scale for both axes sets the axis region to be square.
Adds grid lines to the plot. 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; 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 plots y versus x with a log (base 10) scale for the x axis and linear scale for the y axis
semilogx (x,y)
loglog (x,y)
Example: Type in the Command window and observe the generated plots for the same function:
Notes for plots with logarithmic axes: y y 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 (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.
polar (theta,radius,line,specifiers) (Optional) specifiers that define the type and color of the line and markers.
Vector
Example 1:
Data input
Function File
Output
FUNCTION DEFINITION LINE y y y Defines the file as a function Defines the name of the function Defines the number and order of the input and output arguments.
The word function must be the first word, and must be typed in lowercase letters.
The name of the A list of input function arguments typed inside parentheses.
Input and Output Arguments Function definition line Comments Three Arguments input arguments, two
arguments,
one
output
function A = RectArea[a,b]
Same as above, one output argument can be typed without the brackets. One input variable, two output variables. Three input arguments arguments, no output
function definition line function[mpay,tpay] = loan(amount,rate,years) function[A] RectArea(a,b) function[V,S] = SphereVolArea(r) function trajectory(v,h,g)
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.
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); radius = sqrt((x^2)+(y^2)); % computes for the angle % 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) radius end
COMPARISON BETWEEN SCRIPT FILES AND FUNCTION FILES y y y y y y y 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.