MATLAB basics MATLAB basics • Get to know Matlab • Interact with Matlab • Write and save a program • Run and debug a program • “Loop” and “for” loop structure • Simple 2D plotting • Get help in Matlab
MATLAB basicsMATLAB basics
• Get to know Matlab• Interact with Matlab• Write and save a program• Run and debug a program• “Loop” and “for” loop structure• Simple 2D plotting• Get help in Matlab
Uses of MATLABUses of MATLAB
• MATLAB is a sophisticated MATLAB is a sophisticated mathematical computation tool. It has mathematical computation tool. It has many capabilities, including:many capabilities, including:– Mathematical operationsMathematical operations– Computations with matricesComputations with matrices– Symbolic calculationsSymbolic calculations– Graphical capabilities, including many Graphical capabilities, including many
plotting featuresplotting features• MATLAB can be used in many MATLAB can be used in many
engineering applications.engineering applications.
Command WindowCommand Window
Workspace Workspace WindowWindow
Current Directory Current Directory Window Window
Command History Command History WindowWindow
Start ButtonStart Button
MATLAB DesktopMATLAB Desktop
clcclc – clears the command – clears the command windowwindowclearclear – clears the workspace – clears the workspace
• Type in the Command Type in the Command Window:Window:
2+22+2• The solution was stored The solution was stored
in the default variable in the default variable ansans..
• Then type:Then type: clearclear• Now define C_as:Now define C_as:
C_as=0.6;C_as=0.6;• The semi-colon (The semi-colon (;;) )
prevents the result from prevents the result from being printed to the being printed to the screenscreen
• Only letters, numbers Only letters, numbers and “_” can be used.and “_” can be used.
• Case sensitive.Case sensitive.
Interacting with MATLABInteracting with MATLABScalar variables
matrices
• Define 1D matrix (vector) Define 1D matrix (vector) xx
x=1:0.2:4 orx=1:0.2:4 or x=ones(4,1)x=ones(4,1)• The first index is the The first index is the
number of rows and the number of rows and the second index is the second index is the number of columns.number of columns.
• The solution can also be The solution can also be viewed in workspace.viewed in workspace.
• Then define a 2D matrix:Then define a 2D matrix: y=[1,2,3;4,5,6]y=[1,2,3;4,5,6]• We can change the value We can change the value
of any elements:of any elements:
y(2,3)=5y(2,3)=5• The matrix dimension can The matrix dimension can
also be changed:also be changed: y(4,4)=7y(4,4)=7
Writing a ProgramWriting a Program
• A MATLAB program can be a A MATLAB program can be a collection of command lines and is collection of command lines and is in the form of an in the form of an M-fileM-file
• An An M-fileM-file is to MATLAB what a doc- is to MATLAB what a doc-file is to Microsoft Word.file is to Microsoft Word.
• An M-file is written in An M-file is written in text Editortext Editor..• M-files can be used to:M-files can be used to:
– write programswrite programs– save and reopen a programsave and reopen a program– Fix errors in a programFix errors in a program
Writing an M-FileWriting an M-File• Create a new M-file:Create a new M-file:
– Type Type editedit into the Command into the Command WindowWindow
– or use the menu “File”or use the menu “File”• Type the following code in the Editor:Type the following code in the Editor: epsilon=10; C_as=0.5; r=0:R/20:R; R=5: rho=r/R;
• To insert a comment line in an M-file, To insert a comment line in an M-file, use the comment operator %, then use the comment operator %, then type in your comment. type in your comment.
• After you have typed the code, save it After you have typed the code, save it as “concentration.m”as “concentration.m”
CommentingCommenting• Every time you write a program, it should be Every time you write a program, it should be well-well-
commentedcommented..• MATLAB:MATLAB:
– will not run lines that begin with the comment operatorwill not run lines that begin with the comment operator– shades comments in greenshades comments in green
• Commenting can explain: Commenting can explain: – what the program doeswhat the program does– what the variables in the program representwhat the variables in the program represent– any calculations in the programany calculations in the program– allow programmers to more easily understand your allow programmers to more easily understand your
programprogram– make difficult operations easier to understandmake difficult operations easier to understand– document when code was written and by whomdocument when code was written and by whom– define variables useddefine variables used– help clarify your own thinkinghelp clarify your own thinking
Changing the DirectoryChanging the Directory
• To change your directory, click the “Browse To change your directory, click the “Browse for Folder” button next to where the for Folder” button next to where the Current DirectoryCurrent Directory is shown. is shown.
• Navigate through this window to “My Navigate through this window to “My Computer” and then to where you want to Computer” and then to where you want to save your M file and click “OK.”save your M file and click “OK.”
• You should make sure that your Current You should make sure that your Current Directory is where your file is, otherwise Directory is where your file is, otherwise Matlab will not run it.Matlab will not run it.
Browse for FolderBrowse for Folder
Running an M-fileRunning an M-file
• Make sure that your Current Directory is Make sure that your Current Directory is where your file is. Type where your file is. Type concentrationconcentration into into the Command Window and press enter, or use the Command Window and press enter, or use the “the “DebugDebug” menu.” menu.
• If you typed the code as written on the If you typed the code as written on the previous slide you will get an error. What went previous slide you will get an error. What went wrong?wrong?
• Error checking, also called Error checking, also called debuggingdebugging, helps , helps to verify a program works properly.to verify a program works properly.
• The advantage of an M-file is that we can go The advantage of an M-file is that we can go make the change and run it again without make the change and run it again without having to type all the code again.having to type all the code again.
Syntax ErrorsSyntax Errors
• Syntax errorsSyntax errors are errors in a MATLAB are errors in a MATLAB statement itself, such as spelling or statement itself, such as spelling or punctuation errors.punctuation errors.
sni(pi) ln(x) z = sni(pi) ln(x) z = [1,2,3,4,5[1,2,3,4,5sinsin(pi) (pi) loglog(x) z = [1,2,3,4,5(x) z = [1,2,3,4,5]]
Built-in functions
sin, cos, log are built-in functions in MATLAB. There are more built-in functions we will be using in this class, they are besseli, besselj, besselk, bessely, gamma…
For more information on these functions, please use “help”.
• Run-time errorsRun-time errors occur when illegal operations occur when illegal operations are attempted during program execution.are attempted during program execution.
• One run-time error occurs when attempting to One run-time error occurs when attempting to access an element in a matrix that exceeds access an element in a matrix that exceeds the dimensions of that matrix.the dimensions of that matrix.
• Type the following into the Command Window:Type the following into the Command Window: a = rand(3,4);a = rand(3,4); b = a(7,1);b = a(7,1);
• There are not 7 rows in the matrix A, so an There are not 7 rows in the matrix A, so an error message is generated.error message is generated.
Run-Time ErrorsRun-Time Errors
• Logical errorsLogical errors occur when the program runs occur when the program runs without displaying an error, but produces an without displaying an error, but produces an unexpected result.unexpected result.
• Such errors can be very difficult to find. We Such errors can be very difficult to find. We can compare simple test cases with known can compare simple test cases with known correct results in an attempt to find where correct results in an attempt to find where these errors occur.these errors occur.
• For example, the following code is meant to For example, the following code is meant to determine the volume of a sphere:determine the volume of a sphere:
V=(4/3)*pi*r^2;V=(4/3)*pi*r^2;• Where is the error?Where is the error?
Logical ErrorsLogical Errors
The Concept of For LoopsThe Concept of For Loops• LoopsLoops are MATLAB constructs that allow a sequence of are MATLAB constructs that allow a sequence of
MATLAB statements to beMATLAB statements to be executed more than once. executed more than once.
• ForFor loops repeat a block of commands for loops repeat a block of commands for known known
number of timesnumber of times before the loop is executed.before the loop is executed.
For loop syntax:For loop syntax:
for index = [index for index = [index
matrix]matrix]
command #1command #1
command #2command #2
..
..
endend
Check to see if the index has been exceeded
Other commands
FalseFalse
True: out of True: out of values in index values in index matrixmatrix
A Simple For Loop A Simple For Loop ExampleExample
• The commands in a for loop are executed for The commands in a for loop are executed for each value in the index matrix.each value in the index matrix.
for i=1:5for i=1:5 x=factorial(i)x=factorial(i) endend• What is the value of the variable x in the What is the value of the variable x in the
Workspace?Workspace?• After executing the loop, if we call for After executing the loop, if we call for xx, it has , it has
only one value: the value of the index the final only one value: the value of the index the final time through the loop.time through the loop.
• If all the values shall be saved, use the If all the values shall be saved, use the following code:following code:
for i=1:5for i=1:5 y(i)=factorial(i)y(i)=factorial(i) endend
Creating Matrices With for Creating Matrices With for LoopsLoops
vector_1 stores the value of n:vector_1 stores the value of n:
vector_1 = [1 2 3 4 5]vector_1 = [1 2 3 4 5]
vector_2 stores the square of n:vector_2 stores the square of n:
vector_2 = [1 4 9 16 25]vector_2 = [1 4 9 16 25]
Now we will fill a vector, element by Now we will fill a vector, element by element using a for loop:element using a for loop:
for n=1:5 fpringf('The value of n is now %d\n',n); vector_1(n)=n; vector_2(n)=n^2;end
Try This…Try This…
• An exampleAn example
The CodeThe Code
Nested LoopsNested Loops
• One loop can be written inside another One loop can be written inside another loop. The inner loop is called a loop. The inner loop is called a nested nested looploop. .
• One application is a multiplication table:One application is a multiplication table:for i = 1:3 for j = 1:3 prod = i*j; fprintf('%d * %d = %d \n', i, j, prod); endend
Plotting in 2DPlotting in 2D Use the Use the plot() plot() command:command:
This will create a plotThis will create a plot
of rho vs. Ca_Cas, or of rho vs. Ca_Cas, or dependentdependent
vs. independent.vs. independent.
epsilon=10;C_as=0.5;r=0:R/20:R;R=5;rho=r/R;Ca_Cas=besseli(0,rho*epsilon)/besseli(0,epsilon); plot(rho,Ca_Cas)
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 10
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
Changing the plotChanging the plot
A grid can help to A grid can help to interpolate the value interpolate the value of a function or a set of a function or a set of data.of data.
grid ongrid on
grid offgrid off Adding a Adding a titletitle and and
labelslabels gives more gives more meaning to a plot.meaning to a plot.
title('\rho vs. title('\rho vs. C_A/C_A_s')C_A/C_A_s')
xlabel('\rho')xlabel('\rho') ylabel('C_A/C_A_s')ylabel('C_A/C_A_s')
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 10
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
vs. CA
/CAs
CA
/CA
s
““\rho” is used to input Greek letter \rho” is used to input Greek letter ρ. Use the help feature to . Use the help feature to search for how to input other special characters (under “text search for how to input other special characters (under “text properties”).properties”).
Plotting Multiple Curves on a Plotting Multiple Curves on a FigureFigure
epsilon=10;C_as=0.5;r=0:R/20:R;R=5;rho=r/R;Ca_Cas=besseli(0,rho*epsilon)/besseli(0,epsilon);epsilon2=1;Ca2_Cas=besseli(0,rho*epsilon2)/besseli(0,epsilon2); plot(rho,Ca_Cas,rho,Ca2_Cas) orplot(rho,Ca_Cas)hold onplot(rho,Ca2_Cas)
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 10
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
Changing plot styleChanging plot style
plot(rho,Ca_Cas,'r-.*')hold onplot(rho,Ca2_Cas)axis([-0.1,1.1,-0.1,1.1]);title('\rho vs. C_A/C_A_s')title('\rho vs. C_A/C_A_s')xlabel('\rho')xlabel('\rho')ylabel('C_A/C_A_s')ylabel('C_A/C_A_s')legend('\epsilon = 10','\epsilon = 1',2);text(0,0.2,'prepared for CH561');
Plot the data with a red, dash-dot line with red stars for Plot the data with a red, dash-dot line with red stars for points;points;
Rescale axisRescale axis Add in a titleAdd in a title Add in x, y labelsAdd in x, y labels Add in legendsAdd in legends Add in textAdd in text
0 0.2 0.4 0.6 0.8 1
0
0.2
0.4
0.6
0.8
1
vs. CA
/CAs
CA
/CA
s
prepared for CH561
= 10 = 1
Style reference tableStyle reference tableLine Line typetype
IndicatorIndicator Marker typeMarker type IndicatorIndicator ColorColor IndicatorIndicator
solidsolid -- pointpoint .. blueblue bb
dotteddotted :: circlecircle oo greengreen gg
dash-dotdash-dot -.-. x-markx-mark xx redred rr
dasheddashed ---- plusplus ++ cyancyan cc
starstar ** magentamagenta mm
squaresquare ss yellowyellow yy
diamonddiamond dd blackblack kk
triangle downtriangle down vv
triangle uptriangle up ^̂
triangle lefttriangle left <<
triangle righttriangle right >>
pentagrampentagram pp
hexagramhexagram hh
SubplotsSubplots
• TheThe subplot() subplot() function allows for putting function allows for putting multiple graphs in one figure.multiple graphs in one figure.
• subplot(m,n,p)subplot(m,n,p) divides graphing window divides graphing window into a grid of m rows and n columns, into a grid of m rows and n columns, where p identifies the part of the window where p identifies the part of the window where the plot will be drawn. These where the plot will be drawn. These positions are counted from left to right positions are counted from left to right along each row.along each row.
p = 1p = 1 p = 2p = 2
p = 3p = 3 p = 4p = 4
Examples of SubplotsExamples of Subplots
• To graph sin(x) and cos(x) on the same To graph sin(x) and cos(x) on the same figure in separate plots:figure in separate plots:
subplot(1,2,1);plot(rho,Ca_Cas);title('C_A_1/C_A_s');xlabel('\rho');ylabel('C_A_1/C_A_s');subplot(1,2,2);plot(rho,Ca2_Cas,'r-.*');title('C_A_2/C_A_s');xlabel('\rho');
Saving FiguresSaving Figures
• There are several ways to save plots created in There are several ways to save plots created in MATLAB:MATLAB:– Store the MATLAB code for generating the Store the MATLAB code for generating the
plot in an M-fileplot in an M-file– Save the figure as a .fig file, which is Save the figure as a .fig file, which is
MATLAB’s graphics format, or in any other MATLAB’s graphics format, or in any other standard graphic format.standard graphic format.
– Copy the figure into another document: Copy the figure into another document: Edit>>Copy Figure.Edit>>Copy Figure.
Logarithmic PlotsLogarithmic Plots(pg. 155 [1]; pg. 178 [2])(pg. 155 [1]; pg. 178 [2])
• MATLAB has three kinds of MATLAB has three kinds of logarithmic plotslogarithmic plots::– semilogxsemilogx– semilogysemilogy– loglogloglog
• These plots replace linear scales with logarithmic These plots replace linear scales with logarithmic scales.scales.
• Logarithmic scales are used when a variable Logarithmic scales are used when a variable ranges over many orders of magnitude.ranges over many orders of magnitude.
Getting help in Matlab• Function help• Topic help
Your Turn!Your Turn!
• Need an exampleNeed an example