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 Uses of MATLAB • MATLAB is a sophisticated mathematical computation tool. It has many capabilities, including: – – – – Mathematical operations Computations with matrices Symbolic calculations Graphical capabilities, including many plotting features • MATLAB can be used in many engineering applications. MATLAB Desktop Command Window Workspace Window Current Directory Window Command History Window Start Button clc – clears the command window clear – clears the workspace Interacting with MATLAB Scalar variables • • • • • • • matrices Type in the Command Window: 2+2 The solution was stored in the default variable ans. Then type: clear Now define C_as: • C_as=0.6; The semi-colon (;) prevents the result from being printed to the screen Only letters, numbers and “_” can be used. Case sensitive. • • • • • Define 1D matrix (vector) x x=1:0.2:4 or x=ones(4,1) The first index is the number of rows and the second index is the number of columns. The solution can also be viewed in workspace. Then define a 2D matrix: y=[1,2,3;4,5,6] We can change the value of any elements: y(2,3)=5 The matrix dimension can also be changed: y(4,4)=7 Writing a Program • A MATLAB program can be a collection of command lines and is in the form of an M-file • An M-file is to MATLAB what a docfile is to Microsoft Word. • An M-file is written in text Editor. • M-files can be used to: – write programs – save and reopen a program – Fix errors in a program Writing an M-File • Create a new M-file: – Type edit into the Command Window – or use the menu “File” • 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, use the comment operator %, then type in your comment. • After you have typed the code, save it as “concentration.m” Commenting • Every time you write a program, it should be wellcommented. • MATLAB: – will not run lines that begin with the comment operator – shades comments in green • Commenting can explain: – – – – – – – – what the program does what the variables in the program represent any calculations in the program allow programmers to more easily understand your program make difficult operations easier to understand document when code was written and by whom define variables used help clarify your own thinking Changing the Directory • To change your directory, click the “Browse for Folder” button next to where the Current Directory is shown. • Navigate through this window to “My Computer” and then to where you want to save your M file and click “OK.” • You should make sure that your Current Directory is where your file is, otherwise Matlab will not run it. Browse for Folder Running an M-file • Make sure that your Current Directory is where your file is. Type concentration into the Command Window and press enter, or use the “Debug” menu. • If you typed the code as written on the previous slide you will get an error. What went wrong? • Error checking, also called debugging, helps to verify a program works properly. • The advantage of an M-file is that we can go make the change and run it again without having to type all the code again. Syntax Errors • Syntax errors are errors in a MATLAB statement itself, such as spelling or punctuation errors. sni(pi) ln(x) z = [1,2,3,4,5 sin(pi) log(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 Errors • Run-time errors occur when illegal operations are attempted during program execution. • One run-time error occurs when attempting to access an element in a matrix that exceeds the dimensions of that matrix. • Type the following into the Command Window: a = rand(3,4); b = a(7,1); • There are not 7 rows in the matrix A, so an error message is generated. Logical Errors • Logical errors occur when the program runs without displaying an error, but produces an unexpected result. • Such errors can be very difficult to find. We can compare simple test cases with known correct results in an attempt to find where these errors occur. • For example, the following code is meant to determine the volume of a sphere: V=(4/3)*pi*r^2; • Where is the error? The Concept of For Loops • Loops are MATLAB constructs that allow a sequence of MATLAB statements to be executed more than once. • For loops repeat a block of commands for known number of times before the loop is executed. Check to see if the index has been exceeded False Other commands True: out of values in index matrix For loop syntax: for index = [index matrix] command #1 command #2 . . end A Simple For Loop Example • The commands in a for loop are executed for each value in the index matrix. for i=1:5 x=factorial(i) end • What is the value of the variable x in the Workspace? • After executing the loop, if we call for x, it has only one value: the value of the index the final time through the loop. • If all the values shall be saved, use the following code: for i=1:5 y(i)=factorial(i) end Creating Matrices With for Loops Now we will fill a vector, element by 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 vector_1 stores the value of n: vector_1 = [1 2 3 4 5] vector_2 stores the square of n: vector_2 = [1 4 9 16 25] Try This… • An example The Code Nested Loops • One loop can be written inside another loop. The inner loop is called a nested loop. • 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); end end Plotting in 2D Use the plot() command: 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) 1 0.9 This will create a plot of rho vs. Ca_Cas, or dependent vs. independent. 0.8 0.7 0.6 0.5 0.4 0.3 0.2 0.1 0 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 Changing the plot A grid can help to interpolate the value of a function or a set of data. 0.9 0.8 0.7 grid on grid off vs. CA /CAs 1 As 0.6 title('\rho vs. C_A/C_A_s') xlabel('\rho') ylabel('C_A/C_A_s') A Adding a title and labels gives more meaning to a plot. C /C 0.5 0.4 0.3 0.2 0.1 0 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 “\rho” is used to input Greek letter ρ. Use the help feature to search for how to input other special characters (under “text properties”). 0.9 1 Plotting Multiple Curves on a Figure 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) or plot(rho,Ca_Cas) hold on plot(rho,Ca2_Cas) 1 0.9 0.8 0.7 0.6 0.5 0.4 0.3 0.2 0.1 0 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 Changing plot style Plot the data with a red, dash-dot line with red stars for points; Rescale axis vs. C /C Add in a title = 10 1 =1 Add in x, y labels 0.8 Add in legends Add in text A As As 0.6 A C /C plot(rho,Ca_Cas,'r-.*') 0.4 hold on plot(rho,Ca2_Cas) 0.2 axis([-0.1,1.1,-0.1,1.1]); title('\rho vs. C_A/C_A_s') 0 xlabel('\rho') ylabel('C_A/C_A_s') legend('\epsilon = 10','\epsilon = 1',2); text(0,0.2,'prepared for CH561'); prepared for CH561 0 0.2 0.4 0.6 0.8 1 Style reference table Line type Indicator Marker type Indicator Color Indicator solid - point . blue b dotted : circle o green g dash-dot -. x-mark x red r dashed -- plus + cyan c star * magenta m square s yellow y diamond d black k triangle down v triangle up ^ triangle left < triangle right > pentagram p hexagram h Subplots • The subplot() function allows for putting multiple graphs in one figure. • subplot(m,n,p) divides graphing window into a grid of m rows and n columns, where p identifies the part of the window where the plot will be drawn. These positions are counted from left to right along each row. p=1 p=3 p=2 p=4 Examples of Subplots • To graph sin(x) and cos(x) on the same 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 Figures • There are several ways to save plots created in MATLAB: – Store the MATLAB code for generating the plot in an M-file – Save the figure as a .fig file, which is MATLAB’s graphics format, or in any other standard graphic format. – Copy the figure into another document: Edit>>Copy Figure. Logarithmic Plots (pg. 155 [1]; pg. 178 [2]) • MATLAB has three kinds of logarithmic plots: – semilogx – semilogy – loglog • These plots replace linear scales with logarithmic scales. • Logarithmic scales are used when a variable ranges over many orders of magnitude. Getting help in Matlab • Function help • Topic help Your Turn! • Need an example