Lecture2 - 1 MATLAB FUNDAMENTALS 2 Overview: Functions...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
1 MATLAB FUNDAMENTALS 2 Dr. Vyas Overview: Functions Elements of Programming using Matlab Graphics (plots) with Matlab Functions 1. Matlab allows the user to define customized functions insofar the function definition format is respected. 2. The function must be defined thru function file . Unlike the case in command window where the assignment was global (meaning a number assigned to a variable is retained until cleared or re-assignment is made or the program is closed), the assignment in function file is local . This means that the assignment is confined to the command statement invoking the function. 3. The function definition format is, function [output variables] = function_name (input variables) 4. The variables in the output and input variable list must be separated by commas. 5. The function file extension is *.m 6. To write a function file, open the m-file editor . This is done thru clicking on File menu, selecting New and further left clicking on the M-file. To start with, type the next two lines in the editor just opened. function [y] = good(x) y = x.^3 + sin(x); Now, save the file as “good.m” in the working (current) directory (if appropriate). Next, type the following sequence of commands. >> clear >> x = linspace(0, 2*pi, 9) x = Columns 1 through 7 0 0.7854 1.5708 2.3562 3.1416 3.9270 4.7124 Columns 8 through 9 5.4978 6.2832 >> y ??? Undefined function or variable 'y'. (Note that we did not make any assignment for the variable ‘y’ in the command window)
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
>> good(x) ans = Columns 1 through 7 0 1.1916 4.8758 13.7879 31.0063 59.8520 103.6462 Columns 8 through 9 165.4672 248.0502 One way to evaluate functions at a particular value(s) is via the command, feval >> feval('good', pi) (The quotation marks are one way of using the function handle) ans = 31.0063 >> feval(@good,pi) (The @ symbol is another way of using the function handle) ans = 31.0063 >> good(pi) (As can be observed, it is not always necessary to use function handle) ans = 31.0063 Consider a case of multiple variables and start with a new function definition. function
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 18

Lecture2 - 1 MATLAB FUNDAMENTALS 2 Overview: Functions...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online