Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 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

2 Uses of MATLAB MATLAB is a sophisticated mathematical computation tool. It has many capabilities, including: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 can be used in many engineering applications.

3 Command Window Workspace Window Current Directory Window Command History Window Start Button MATLAB Desktop clc – clears the command window clear – clears the workspace

4 Type in the Command Window:Type in the Command Window: 2+2 2+2 The solution was stored in the default variable ans.The solution was stored in the default variable ans. Then type:Then type: clear clear Now define C_as:Now define C_as: C_as=0.6; C_as=0.6; The semi-colon (;) prevents the result from being printed to the screenThe semi-colon (;) prevents the result from being printed to the screen Only letters, numbers and “_” can be used.Only letters, numbers and “_” can be used. Case sensitive.Case sensitive. Interacting with MATLAB Scalar variablesmatrices Define 1D matrix (vector) xDefine 1D matrix (vector) x x=1:0.2:4 or x=1:0.2:4 or x=ones(4,1) x=ones(4,1) The first index is the number of rows and the second index is the number of columns.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.The solution can also be 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 of any elements:We can change the value of any elements: y(2,3)=5 y(2,3)=5 The matrix dimension can also be changed:The matrix dimension can also be changed: y(4,4)=7 y(4,4)=7

5 Writing a Program A MATLAB program can be a collection of command lines and is in the form of an M-fileA 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 doc- file is to Microsoft Word.An M-file is to MATLAB what a doc- file is to Microsoft Word. An M-file is written in text Editor.An M-file is written in text Editor. M-files can be used to:M-files can be used to: –write programs –save and reopen a program –Fix errors in a program

6 Writing an M-File Create a new 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: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.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”After you have typed the code, save it as “concentration.m”

7 Commenting Every time you write a program, it should be well- commented.Every time you write a program, it should be well- commented. MATLAB:MATLAB: –will not run lines that begin with the comment operator –shades comments in green Commenting can explain: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

8 Changing the Directory To change your directory, click the “Browse for Folder” button next to where the Current Directory is shown.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.”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.You should make sure that your Current Directory is where your file is, otherwise Matlab will not run it. Browse for Folder

9 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.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?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.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.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.

10 Syntax Errors Syntax errors are errors in a MATLAB statement itself, such as spelling or punctuation 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”.

11 Run-time errors occur when illegal operations are attempted during program execution.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.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: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 error message is generated.There are not 7 rows in the matrix A, so an error message is generated. Run-Time Errors

12 Logical errors occur when the program runs without displaying an error, but produces an unexpected result.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.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:For example, the following code is meant to 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 Errors Logical Errors

13 The Concept of For Loops Loops are MATLAB constructs that allow a sequence of MATLAB statements to be executed more than once.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.For loops repeat a block of commands for known number of times before the loop is executed. For loop syntax: for index = [index matrix] command #1 command #2..end Check to see if the index has been exceeded Other commands False True: out of values in index matrix

14 A Simple For Loop Example The commands in a for loop are executed for each value in the index matrix.The commands in a for loop are executed for each value in the index matrix. for i=1:5 for i=1:5 x=factorial(i) x=factorial(i) end end What is the value of the variable x in the Workspace?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.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:If all the values shall be saved, use the following code: for i=1:5 for i=1:5 y(i)=factorial(i) y(i)=factorial(i) end end

15 Creating Matrices With for Loops 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] Now we will fill a vector, element by element using a for loop: 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

16 Try This… An exampleAn example

17 The Code

18 Nested Loops One loop can be written inside another loop. The inner loop is called a nested loop.One loop can be written inside another loop. The inner loop is called a nested loop. 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); end

19 Plotting in 2D Use the plot() command: Use the plot() command: This will create a plot This will create a plot of rho vs. Ca_Cas, or dependent of rho vs. Ca_Cas, or dependent 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)

20 Changing the plot A grid can help to interpolate the value of a function or a set of data. A grid can help to interpolate the value of a function or a set of data. grid on grid on grid off grid off Adding a title and labels gives more meaning to a plot. Adding a title and labels gives more meaning to a plot. 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') “\rho” is used to input Greek letter. Use the help feature to search for how to input other special characters (under “text properties”). “\rho” is used to input Greek letter ρ. Use the help feature to search for how to input other special characters (under “text properties”).

21 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)

22 Changing plot style plot(rho,Ca_Cas,'r-.*') hold on plot(rho,Ca2_Cas) axis([-0.1,1.1,-0.1,1.1]); title('\rho vs. C_A/C_A_s') xlabel('\rho')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 points; Plot the data with a red, dash-dot line with red stars for points; Rescale axis Rescale axis Add in a title Add in a title Add in x, y labels Add in x, y labels Add in legends Add in legends Add in text Add in text

23 Style reference table Line type Indicator Marker type IndicatorColorIndicator solid-point.blueb dotted:circleogreeng dash-dot-.x-markxredr dashed--plus+cyanc star*magentam squaresyellowy diamonddblackk triangle down v triangle up ^ triangle left < triangle right > pentagramp hexagramh

24 Subplots The subplot() function allows for putting multiple graphs in one figure.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.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 = 2 p = 3 p = 4

25 Examples of Subplots To graph sin(x) and cos(x) on the same figure in separate plots: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');

26 Saving Figures There are several ways to save plots created in MATLAB: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.

27 Logarithmic Plots (pg. 155 [1]; pg. 178 [2]) MATLAB has three kinds of logarithmic plots:MATLAB has three kinds of logarithmic plots: –semilogx –semilogy –loglog These plots replace linear scales with logarithmic scales.These plots replace linear scales with logarithmic scales. Logarithmic scales are used when a variable ranges over many orders of magnitude.Logarithmic scales are used when a variable ranges over many orders of magnitude.

28 Getting help in Matlab Function help Topic help

29 Your Turn! Need an exampleNeed an example


Download ppt "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."

Similar presentations


Ads by Google