MatlabMatlab
TextbooksTextbooks
Required: Required: Introduction to MATLAB for Engineers, by Palm (3, by Palm (3rdrd edition) edition)
Purchasing MATLAB SoftwarePurchasing MATLAB Software
Mathworks web site: Mathworks web site: ((http://www.mathworks.comhttp://www.mathworks.com). ).
UH Bookstore—be sure to get version UH Bookstore—be sure to get version 77
UH-IT DepartmentUH-IT Department
About MATLABAbout MATLAB
a computer a computer programming languageprogramming language
a a software environmentsoftware environment for using the for using the language effectivelylanguage effectively
MATLAB is…MATLAB is…
Two modes of operationTwo modes of operation
Interactive calculator modeInteractive calculator mode Script mode: execution of complete Script mode: execution of complete
programs programs script files script files
About MATLABAbout MATLAB
Running MATLAB creates one or more windowsRunning MATLAB creates one or more windows
One is called the One is called the MATLAB Desktop: MATLAB Desktop: Primary Primary graphical user interface for MATLABgraphical user interface for MATLAB
Contains and manages all other windows that are Contains and manages all other windows that are part of MATLABpart of MATLAB
According to the configuration some windows may According to the configuration some windows may be visible and some may not. You can see this be visible and some may not. You can see this information in the View Menuinformation in the View Menu
About MATLABAbout MATLAB
About MATLAB DesktopAbout MATLAB Desktop
MATLAB Desktop Windows:MATLAB Desktop Windows:
– Command Window:Command Window: Primary place to interact with Primary place to interact with MATLAB. Place where the user issues the MATLAB. Place where the user issues the commands. The MATLAB command prompt is the commands. The MATLAB command prompt is the symbol >>symbol >>
– Command History:Command History: Running history of prior Running history of prior commands issued in the Command Window.commands issued in the Command Window.
About MATLAB DesktopAbout MATLAB Desktop
MATLAB Desktop Windows:MATLAB Desktop Windows:
– Workspace:Workspace: GUI for viewing, loading, and saving GUI for viewing, loading, and saving MATLAB variables.MATLAB variables.
– Launch Pad:Launch Pad: Tree layout for access to tools, Tree layout for access to tools, demos and documentationdemos and documentation
– Current Directory:Current Directory: GUI for directory and file GUI for directory and file manipulation in MATLAB.manipulation in MATLAB.
About MATLAB DesktopAbout MATLAB Desktop
MATLAB Desktop Windows:MATLAB Desktop Windows:
– Help:Help: GUI for finding and viewing on-line GUI for finding and viewing on-line documentation.documentation.
– Array Editor:Array Editor: GUI for modifying the content of GUI for modifying the content of MATLAB variablesMATLAB variables
– Editor/Debugger:Editor/Debugger: Text editor and debugger for Text editor and debugger for MATLAB text files.MATLAB text files.
About MATLAB DesktopAbout MATLAB Desktop
What does Matlab What does Matlab understand?understand?
Real numbers: 1 -14 7.65432 2e3Real numbers: 1 -14 7.65432 2e3 Complex numbers: 2+3i 4-6j 2iComplex numbers: 2+3i 4-6j 2i Arrays of numbers: [1,2,3] [1,2;3,4]Arrays of numbers: [1,2,3] [1,2;3,4] Strings: ‘I wish I knew that!’Strings: ‘I wish I knew that!’
Basics: Basic OperationsBasics: Basic Operations
SymbolSymbol OperationOperation MATLABMATLAB^̂ exponentiation: aexponentiation: abb a^ba^b
** multiplication: abmultiplication: ab a*ba*b
// right division: a/b =right division: a/b = a/ba/b
\\ left division: a\b = left division: a\b = a\ba\b
++ addition: a + baddition: a + b a+ba+b
-- subtraction: a-b subtraction: a-b a-ba-b
b
a
a
b
Precedence Operation
FirstFirst Parentheses, evaluated starting Parentheses, evaluated starting with the innermost pair.with the innermost pair.
SecondSecond Exponentiation, evaluated from Exponentiation, evaluated from left to right.left to right.
ThirdThird Multiplication and division with Multiplication and division with equal precedence, evaluated from equal precedence, evaluated from left to right.left to right.
FourthFourth Addition and subtraction with Addition and subtraction with equal precedence, evaluated from equal precedence, evaluated from left to right.left to right.
Basics: Rules of PrecedenceBasics: Rules of Precedence
precedence examplesprecedence examples
» 8 + 3 * 58 + 3 * 5 (8 + (3 * 5)) = 23(8 + (3 * 5)) = 23
» 4 ^ 2 – 12 – 8 / 4 * 24 ^ 2 – 12 – 8 / 4 * 2 ((4 ^ 2) – 12 – ((8 / 4) * 2))) = 0((4 ^ 2) – 12 – ((8 / 4) * 2))) = 0
» 3 * 4 ^ 2 + 53 * 4 ^ 2 + 5 ((3 * (4 ^ 2)) + 5) = 53((3 * (4 ^ 2)) + 5) = 53
» 27 ^ 1 / 3 + 32 ^ 0.227 ^ 1 / 3 + 32 ^ 0.2 (((27 ^ 1) / 3 )+ (32 ^ 0.2))=11(((27 ^ 1) / 3 )+ (32 ^ 0.2))=11
Basics: Rules of PrecedenceBasics: Rules of Precedence
Basics: VariablesBasics: Variables Variable is a symbol used to contain a valueVariable is a symbol used to contain a value
MATLAB has some rules to name variablesMATLAB has some rules to name variables– Variables names are case sensitiveVariables names are case sensitive
» BOB, Bob, bob, BoB BOB, Bob, bob, BoB all different! all different!
– Variables names can contain up to 31 characters. Any Variables names can contain up to 31 characters. Any additional characters are ignoredadditional characters are ignored
– Variable names must start with a letter, followed by any Variable names must start with a letter, followed by any number of letters, digits or underscores. Punctuation number of letters, digits or underscores. Punctuation characters are not allowed, because most of them have a characters are not allowed, because most of them have a special meaning in MATLABspecial meaning in MATLAB
Some names cannot be used for variables: Some names cannot be used for variables: for, end, for, end, if, while, function, return, elseif, case, otherwise, if, while, function, return, elseif, case, otherwise, switch, continue, else, try, catch, global, persistent, switch, continue, else, try, catch, global, persistent, breakbreak
If you try to use any of these If you try to use any of these reserved wordsreserved words as a as a variable, MATLAB will report an errorvariable, MATLAB will report an error
Of course, you can use words similar by capitalizing Of course, you can use words similar by capitalizing one or more lettersone or more letters
Also, MATLAB has a number of special variables Also, MATLAB has a number of special variables and constantsand constants
Basics: VariablesBasics: Variables
Basics: Special Variables and ConstantsBasics: Special Variables and Constants
Name Descriptionansans Default variable name used for resultsDefault variable name used for results
epseps specifies accuracy of f.p. precisionspecifies accuracy of f.p. precision
i,ji,j imaginary unit, sqrt(-1)imaginary unit, sqrt(-1)
InfInf infinityinfinity
NaNNaN undefined numerical resultundefined numerical result
pipi
realmaxrealmax largest real f.p. # on THIS computerlargest real f.p. # on THIS computer
realminrealmin smallest real f.p. # on THIS computersmallest real f.p. # on THIS computer
BasicsBasics Assignment or replacement operator: =Assignment or replacement operator: =
It works different than the equal sign: the variable It works different than the equal sign: the variable on the left-hand side is replaced by the value on the left-hand side is replaced by the value generated by the right-hand side. Therefore, only generated by the right-hand side. Therefore, only one variable name must be in the left-hand sideone variable name must be in the left-hand side– x = x – 2x = x – 2– 6 = x 6 = x NOT VALID!!! NOT VALID!!!
The right-hand side must have a computable valueThe right-hand side must have a computable value– x = 5 + y; x = 5 + y; Is y defined?Is y defined?
BasicsBasics
Example: Volume of a circular cylinderExample: Volume of a circular cylinderGiven a circular cylinder with height 15m and radius 8 m, Given a circular cylinder with height 15m and radius 8 m, find the radius of a cylinder of the same height but with a find the radius of a cylinder of the same height but with a volume that is 20% larger.volume that is 20% larger.
Solution AlgorithmSolution Algorithm
Calculate current volumeCalculate current volume Calculate desired volumeCalculate desired volume Determine new radius by rewriting Determine new radius by rewriting
volume equation in terms of radius:volume equation in terms of radius:
BasicsBasics The formula for volume is V=The formula for volume is V=rr22hh The radius is given by:The radius is given by:
πh
Vr
>> r = 8;>> r = 8;
>> h = 15;>> h = 15;
>> V = pi*r^2*h>> V = pi*r^2*h
>> newV = 1.2*V>> newV = 1.2*V
>> newr = sqrt(newV/(pi*h))>> newr = sqrt(newV/(pi*h))
ans = 8.7636ans = 8.7636
Basics: CommandsBasics: CommandsCommand Descriptionclc clears Command window
clear removes all variables
clear var1 var2 removes listed variables
exist (‘name’) determines if name (file or var) exists
quit Stops MATLAB
who lists current variables
whos lists current variables with sizes
: generates array
, separates elements of array
; suppresses screen printing, also new line in array
… continues a line
Basics: Complex NumbersBasics: Complex Numbers complex numbercomplex number ex: ex:
» s = 3 + 7is = 3 + 7i» w = 5 – 9iw = 5 – 9i
MATLAB Ex.MATLAB Ex.– Given Given x = -5 + 9ix = -5 + 9i and and y = 6 – 2iy = 6 – 2i– findfind
• x + y=x + y=1+7i1+7i• x*y =x*y = -12 + 64i-12 + 64i• x/y = x/y = -1.2 + 1.1i-1.2 + 1.1i
Some Simple FunctionsSome Simple Functions
sin(x)sin(x)
sqrt(x)sqrt(x)
acos(x)acos(x)
exp(x)exp(x)
log(x)log(x)
InterpretationInterpretation
sin(180) ?????sin(180) ????? acos(.5) ?????acos(.5) ????? exp(1) ?????exp(1) ????? log(10) ?????log(10) ?????
Polynomials in MatlabPolynomials in Matlab
A polynomial is represented by its array A polynomial is represented by its array of coefficients, beginning with the of coefficients, beginning with the “leading” coefficient (coefficient of “leading” coefficient (coefficient of highest power):highest power):
]0,1,2,4[x4x2x]2,4,3[2x4x3
32
2
Special Polynomial FunctionsSpecial Polynomial Functions
polyval(a,x): evaluates polynomial polyval(a,x): evaluates polynomial whose coefficients are in array a at the whose coefficients are in array a at the point xpoint x
roots(a): returns a vector containing all roots(a): returns a vector containing all of the roots of the polynomial whose of the roots of the polynomial whose coefficients are in the array acoefficients are in the array a
poly(v): returns the coefficient vector of poly(v): returns the coefficient vector of a polynomial whose roots are stored in a polynomial whose roots are stored in the vector vthe vector v
Polynomial ExamplesPolynomial Examples
>> a=[2,4,-1,5];>> a=[2,4,-1,5];>> polyval(a,0)>> polyval(a,0)
ans =ans =
55>> poly([1, 2, 3])>> poly([1, 2, 3])
ans =ans =
1 -6 11 -61 -6 11 -6
>> v=roots(a)>> v=roots(a)
v =v =
-2.5722 -2.5722
0.2861 + 0.9434i0.2861 + 0.9434i
0.2861 - 0.9434i0.2861 - 0.9434i
Plotting in MatlabPlotting in Matlab
The basic command to plot a set of points in the The basic command to plot a set of points in the plane is plot(x,y)plane is plot(x,y)
x is a vector containing the horizontal coordinatesx is a vector containing the horizontal coordinates y is a vector containing the vertical coordinatesy is a vector containing the vertical coordinates x & y must be the same size—either both row vectors x & y must be the same size—either both row vectors
or both column vectorsor both column vectors The plot actually appears in a separate window, The plot actually appears in a separate window,
called a “figure” window.called a “figure” window.
Plotting ExamplePlotting Example
>> x=[0:.01:10]; %generate x values>> x=[0:.01:10]; %generate x values
>> y=sin(x); %generate y values --sin function >> y=sin(x); %generate y values --sin function
%applied to array of x’s%applied to array of x’s
>> figure(1) %give number to figure>> figure(1) %give number to figure
>> plot(x,y),title('My first Plot'),xlabel('x axis'),...>> plot(x,y),title('My first Plot'),xlabel('x axis'),...
ylabel('y axis')ylabel('y axis')
CommandCommand DescriptionDescriptionplot(x,y)plot(x,y) Generates plot.Generates plot.
title(‘text’)title(‘text’) Puts title on plot.Puts title on plot.
xlabel(‘text’)xlabel(‘text’) Adds label to horizontal axis.Adds label to horizontal axis.
ylabel(‘text’)ylabel(‘text’) Adds label to vertical axis.Adds label to vertical axis.
legendlegend Places a legendPlaces a legend
figure nfigure n Opens a new figure window numbered nOpens a new figure window numbered n
hold onhold on Holds on the current graphHolds on the current graph
Plotting in MATLABPlotting in MATLAB
Plotting in MATLABPlotting in MATLAB Some Plot OptionsSome Plot Options
COLORSCOLORS SYMBOLSSYMBOLS LINE TYPESLINE TYPES
y yellowy yellow . point . point - solid- solid
m magentam magenta o circleo circle : dotted: dotted
c cyanc cyan x x-markx x-mark -. dash dot-. dash dot
r redr red + plus+ plus -- dashed-- dashed
g greeng green * star* star
b blueb blue s squares square
w whitew white d diamondd diamond
k blackk black v,^,<,> trianglesv,^,<,> triangles
Matlab FilesMatlab Files
Script & function files—plain ASCII, Script & function files—plain ASCII, extension .mextension .m
MAT files—binary file, used to “save” MAT files—binary file, used to “save” workspace variables, extension .matworkspace variables, extension .mat
Formatting CommandsFormatting Commands
Rational approximationRational approximation
43/743/7
format ratformat rat
16 digits (15 decimals) plus exponent;16 digits (15 decimals) plus exponent;
6.379243784781294e6.379243784781294e--0404
format long eformat long e
5 digits (4 decimals) plus exponent;5 digits (4 decimals) plus exponent;
6.3792e+036.3792e+03
format short eformat short e
16 digits;16 digits;
17.2748402946354717.27484029463547
format longformat long
4 decimal digits (the default);4 decimal digits (the default);
13.674513.6745
format shortformat short
Description and ExampleDescription and ExampleCommandCommand
>> pi
ans =
3.1416
>> format long
>> pi
ans =
3.14159265358979
>> format rat
>> pi
ans =
355/113
Controlling Input and OutputControlling Input and Output The The dispdisp Function: Useful to control the output Function: Useful to control the output
disp: Display array.disp: Display array.
disp(X) displays the array, without printing the array name. disp(X) displays the array, without printing the array name. It's the same as leaving the semicolon off an expression It's the same as leaving the semicolon off an expression except that empty arrays don't display. If X is a string, the except that empty arrays don't display. If X is a string, the text is displayed.text is displayed.
EXAMPLES:EXAMPLES:>> disp(X) displays the value of variable X, but not its name>> disp(X) displays the value of variable X, but not its name
>> disp(‘The value of X is:’) displays the string>> disp(‘The value of X is:’) displays the string The value of X is:The value of X is:but no numberbut no number
Controlling Input and OutputControlling Input and Output The The num2strnum2str Function: Useful to make the output Function: Useful to make the output
look betterlook betternum2str: Convert number to string.num2str: Convert number to string.
T=num2str(X) converts the array X into a string T=num2str(X) converts the array X into a string representation T with about 4 digits and an exponent if representation T with about 4 digits and an exponent if required. Allows display of label on same line as value. required. Allows display of label on same line as value.
>> x=3.24567;>> x=3.24567;
>> disp(['The value of x is ',num2str(x),'ft'])>> disp(['The value of x is ',num2str(x),'ft'])
The value of x is 3.2457ftThe value of x is 3.2457ft
Controlling Input and OutputControlling Input and Output
The The inputinput Function: Used to get interactive input. Function: Used to get interactive input. input: Prompt for user input. input: Prompt for user input.
R = input('How many apples') gives the user the prompt in R = input('How many apples') gives the user the prompt in the text string and waits for input from the keyboard. The the text string and waits for input from the keyboard. The input can be any MATLAB expression, which is evaluated, input can be any MATLAB expression, which is evaluated, using the variables in the current workspace, and the using the variables in the current workspace, and the result returned in R. If the user presses the return key result returned in R. If the user presses the return key without entering anything, INPUT returns an empty matrix.without entering anything, INPUT returns an empty matrix.
R = input('What is your name','s') gives the prompt in the R = input('What is your name','s') gives the prompt in the text string and waits for character string input. The typed text string and waits for character string input. The typed input is not evaluated; the characters are simply returned input is not evaluated; the characters are simply returned as a MATLAB string.as a MATLAB string.
Controlling Input and OutputControlling Input and Output
The The MenuMenu Function: Used to get interactive input by Function: Used to get interactive input by selection of an alternative from a menu.selection of an alternative from a menu. k = menu(‘title’,’option1’,’option2’,…) k = menu(‘title’,’option1’,’option2’,…)
choices=['B','D','F'];choices=['B','D','F'];
k=menu('Whodoyouwant?',choices(1),choices(2),choices(3));k=menu('Whodoyouwant?',choices(1),choices(2),choices(3));
disp(['You picked ',choices(k)])disp(['You picked ',choices(k)])
Input from FileInput from File
load– as a command or as a function, load– as a command or as a function, requires each line in file has same requires each line in file has same number of values, loads entire contents of number of values, loads entire contents of file into an arrayfile into an array
>>load data.txt;>>load data.txt; % %name of array will be dataname of array will be data
>>load(‘new.txt’);>>load(‘new.txt’); % %name of array will be newname of array will be new
>>mydata = load(‘proj3.txt’); >>mydata = load(‘proj3.txt’); %name of array will be mydata%name of array will be mydata
Top Related