1 / 28

Basis of Mathematical Modeling

Basis of Mathematical Modeling. LECTURE 2 Programming in MATLAB. Dr. N.K. Sakhnenko, PhD, Professor Associate. Outline. M-files: scripts and functions Types of functions Control flow statements. M-files. The MATLAB product provides a powerful programming language, as well

jace
Download Presentation

Basis of Mathematical Modeling

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Basis of Mathematical Modeling LECTURE 2 Programming in MATLAB Dr. N.K. Sakhnenko, PhD, Professor Associate

  2. Outline • M-files: scripts and functions • Types of functions • Control flow statements

  3. M-files The MATLAB product provides a powerful programming language, as well as an interactive computational environment. Files that contain code in the MATLAB language are called M-files. You create M-files using a text editor, then use them as you would any other MATLAB function or command. There are two kinds of M-files: • Scripts,which do not accept input arguments or return output arguments. They operate on data in the workspace. • Functions,which can accept input arguments and return output arguments. Internal variables are local to the function. Create a new M-file by selecting the File->New->M-file menu item or by clicking the new-file button.

  4. Scripts When you invoke a script, MATLAB simply executes the commands found inthe file. Scripts can operate on existing data in the workspace, or they cancreate new data on which to operate. Although scripts do not return outputarguments, any variables that they create remain in the workspace, to beused in subsequent computations. In addition, scripts can produce graphicaloutput using functions like plot.

  5. Scripts Create a new M-file and type following: x=[-1:0.1:1]; f=sin(x); plot(x,f) Save the file as mydemo.m. You have just created a MATLAB script file. Typing mydemo in the Command window causes the statements in the script file mydemo.m to be executed. To run this file you can also use F5 or Debug->Run menu item.

  6. Functions Functions areM-files that can accept input arguments and return outputarguments. The names of the M-file and of the function should be the same.Functions operate on variables within their own workspace, separate from theworkspace you access at the MATLAB command prompt. The first line of a function M-file starts with the keyword function. It givesthe function name and order of arguments. In this case, there are up to twoinput arguments and one output argument.

  7. Functions Create a new M-file and type following: function f=myfun(x) f=exp(x).*sqrt((x.^3+2)./(x.^4+3)); Save the file as myfun.m. You now have a MATLAB function with one input and one output argument. This function calculates the value of the expression To use the function type in the command window >> y=myfun(1)% x can a matrix as well y = 2.3541 The first line of the function declares the function name, input arguments and output arguments; without this line the file would be the script file.

  8. Multiple inputs This function calculates the value of the expression function f=myfun1(x,y,z) f=sqrt(x.^2+y.^2+z.^2); To use the function type in the command window >> myfun1(1,0,2) ans = 2.2361 >> x=[1 2]; y=[0 -3]; z=[2 0]; >> myfun1(x,y,z) ans = 2.2361 3.6056

  9. Multiple outputs Create the M-file function [f,g]=myfun2(x,y,z) f=sqrt(x.^2+y.^2+z.^2); g=x+y+z; Type in the command window >> [f,g]=myfun2(1,0,2) f = 2.2361 g = 3

  10. Types of Functions • MATLAB offers several different types of functions to use in your • programming. • Handle-Functions • Inline-Functions • Primary and Subfunctions

  11. Function Handles A function handle is typically passed in an argument list to other functions, which can then execute, or evaluate, the function using the handle. Construct a function handle in MATLAB using the at sign, @, before the function name. The following example creates a function handle for the sin function and assigns it to the variable fhandle. fhandle = @sin; Evaluate a function handle using the MATLAB feval function. >> feval(fhandle,1) % or feval(@sin,1) ans = 0.8415 When you call plot with a handle to the sin function and the argument shown below, the resulting evaluation produces a sine wave plot. >>plot(feval(fhandle,0:0.01:2*pi)) % or plot(feval(@sin,0:0.01:2*pi)) This function that doesnot require an M-file.

  12. Inline functions Example 2. >> f1 = inline('sin(alpha*x)') f1 = Inline function: f1(alpha,x) = sin(alpha*x) >> f1(1,pi) ans = 1.2246e-016 If the function variables are in the wrong order, you can specify the desired variables explicitly with the inline argument list. g = inline('sin(alpha*x)','x','alpha') Syntax g = inline(expr) g = inline(expr,arg1,arg2,...) Example 1. >> f = inline('3*sin(2*x.^2)') f = Inline function: f(x) = 3*sin(2*x.^2) >> f(0) ans = 0

  13. Primary and Subfunctions Function M-files can contain code for more than one function. The first function in the file is the primary function, the function invoked with the M-file name. Additional functions within the file are subfunctions that are only visible to the primary function or other subfunctions in the same file. Each subfunction begins with its own function definition line. The functions immediately follow each other. The various subfunctions can occur in any order, as long as the primary function appears first.

  14. Primary and Subfunctions function avg = newstats(u) % Primary function % NEWSTATS Find mean with internal functions. n = length(u); avg = mean(u,n); function a = mean(v,n) % Subfunction % Calculate average. a = sum(v)/n; >> u=[7 3 5] >> f=newstats(u) f = 5

  15. Function Functions A class of functions called “function functions” works with nonlinear functionsof a scalar variable. That is, one function works on another function. Thefunction functions include • Zero finding • Optimization • Numerical Integration • Ordinary differential equations MATLAB represents the nonlinear function by a function M-file.

  16. Control flow statements In their basic forms, these MATLAB flow control statements operate like those in most computer languages. Indenting the statements of a loop or conditional statements is optional, but it helps readability to follow a standard convention.

  17. Relations and logical operators • Comparisons in MATLAB are performed with the aid of the following operators. Operator Description • < Less than • <= Less than or equal to • > Greater • >= Greater or equal to • == Equal to • ~= Not equal to • There are three logical operators available in MATLAB • Logical operator Description • | And • & Or • ~ Not • E.g.: condition in MATLAB has the form (-1<=х) &(х<2)

  18. The if statement The if statement evaluates a logical expression and executes a group of statements when the expression is true. An end keywords, which matches the if, terminates the last group of statements. The elseif and else keywords are optional. Syntax of the simplest form of the construction under discussion is if expression commands end This construction is used if there is one alternative only. Two alternatives require the construction if expression commands (evaluated if expression is true) else commands (evaluated if expression is false) end

  19. The if statement If there are several alternatives one should use the following construction if expression1 commands (evaluated if expression 1 is true) elseif expression 2 commands (evaluated if expression 2 is true) elseif … ... else commands (executed if all previous expressions evaluate to false) end

  20. The if statement Funding the real roots of the square equation function [x1,x2]=root2(a,b,c) % calculation of the discriminant D=b^2-4*a*c; if D<0 error (‘complex roots') end % funding the roots x1=(-b+sqrt(D))/a/2; x2=(-b-sqrt(D))/a/2; >> [x1,x2]=root2(1,2,-1) or >> [x1,x2]=root2(1,2,10)

  21. The if statement function ifdem(a) % Example of using if-elseif-else if (a==0) disp('a is equal to 0') elseif a==1 disp('a is equal to 1') elseif a==2 disp('a is equal to 2') elseif a>=3 disp ('a is greater or equal to 3') else disp('a is less than 3 and distinct from 0, 1 and 2') end >> ifdem(1) a is equal to 1 >> ifdem(1.3) a is less than 3 and distinct from 0, 1 and 2 >> ifdem(3) a is greater or equal to 3

  22. Theswitchstatement The switch statement executes groups of statements based on the value of a variable or expression. The keywords case and otherwise delineate the groups. Only the first matching case is executed. There must always be an end to match the switch. Syntax of the switch-caseconstruction is switch expression (scalar or string) case value1 (executes if expression evaluates to value1) commands case value2 (executes if expression evaluates to value2) commands ... otherwise statements end Switch compares the input expression to each case value. Once the match is found it executes the associated commands. See help switch for more information.

  23. The for loop The for loop repeats a group of statements a fixed, predetermined number of times. A matching end delineates the statements. for count=start:step:final statements end If step=1 we can omit it. >> for i=1:5 i^2 end ans = 1 ans = 4 ans = 9 ans = 16 ans = 25

  24. The for loop >> x=[0:pi/30:2*pi]; >> for a=-0.1:0.02:0.1 y=(1-exp(a*x)).*sin(x); hold on plot(x,y) end Hold on adds every new graph in current window

  25. The for loop The following calculates the sum >> S=0; >> for k=1:1:20 S=S+1/factorial(k); end >> S S = 3.4366

  26. The for loop The for loops can be nested H = zeros(5); for k=1:5 for l=1:5 H(k,l) = 1/(k+l-1); end end H Matrix H created here is called the Hilbert matrix. First command assigns a space in computer'smemory for the matrix to be generated. This is added here to reduce the overhead that is requiredby loops in MATLAB.

  27. The while loop The while loop repeats a group of statements an indefinite number of times under control of a logical condition. A matching end delineates the statements. The general form of a while loop is: while expression statements end The statement will be repeatedly executed as long as the expression remains true.

  28. The while loop E.g., for a given number a, the following computes and displays the smallest nonnegative integer n such that 2n>a: function whiledem(a) n=0; while 2^n<=a n=n+1; end n Using of this programm >> whiledem(1) n = 1 >> whiledem(3) n = 2

More Related