computer applications lab lab 4 functions and script files · 2016-02-06 · functions functions...
TRANSCRIPT
![Page 1: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/1.jpg)
Computer Applications LabComputer Applications LabLab 4Lab 4
Functions and Script Files Functions and Script Files
Chapter 3Chapter 3Chapter 3Chapter 3Sections 1,2,3,4Sections 1,2,3,4
Dr. Iyad Jafar
Adapted from the publisher slides
![Page 2: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/2.jpg)
OutlineOutline
� Passing function arguments
� Common mathematical functions in Matlab
� Script files� Script files
� User-defined functions
� Importing and Exporting Data
2
![Page 3: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/3.jpg)
Passing Function ArgumentsPassing Function Arguments
3
![Page 4: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/4.jpg)
Passing Function ArgumentsPassing Function Arguments
4
![Page 5: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/5.jpg)
Common Mathematical Common Mathematical FunctionsFunctions
5
![Page 6: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/6.jpg)
Common Mathematical Common Mathematical FunctionsFunctions
>> x = 3 + 4j
>> abs(x)
ans = 5
>> angle(x)
ans = 53.1301
6
>> conj(x)
ans = 3 -4j
>> imag(x)
ans = 4
>> real(x)
ans = 3
![Page 7: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/7.jpg)
Common Mathematical Common Mathematical FunctionsFunctions
7
>> x = [5,7,15] ; >> y = sqrt(x) ; y =
2.2361 2.6358 3.8730 >> ceil(y) ans = 3,3,4>> fix(y) ans = 2,2,3
>> floor(y) ans = 2,2,3>> round(y) ans = 2,3,4>> sign(y) Ans = 1 1 1
![Page 8: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/8.jpg)
Common Mathematical Common Mathematical FunctionsFunctions
8
![Page 9: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/9.jpg)
Common Mathematical Common Mathematical FunctionsFunctions
9
![Page 10: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/10.jpg)
Common Mathematical Common Mathematical FunctionsFunctions
10
![Page 11: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/11.jpg)
Script Files Script Files -- IntroductionIntroduction
� Up to this point, we have used Matlab in the interactive mode (commands are entered in the Command window) .
� The interactive mode is desirable when we have few commands.few commands.
� For larger problems we usually use a Script file.
� Basically, the script file contains the same Matlab commands that we type on the command prompt (we don’t have to retype everything if we want to execute/change the commands again.
11
![Page 12: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/12.jpg)
Script Files Script Files -- CreationCreation
� Use the Matlab editor/debugger to create your script file. Available from File>New>M-file or by clicking the new M-file shortcut .
� Enter your commands as desired
� Use
◦ ‘;’ to suppress the result of commands
◦ ‘%’ to insert comments; inline or full-line comments
� Script files are saved in Matlab with .m extension.
� Run your script file by typing fileName.m on the command prompt or click on the run shortcut in the editor .
12
![Page 13: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/13.jpg)
Script Files Script Files -- ExampleExample
Problem
� The speed v of a falling object dropped with no initial velocity is given as a function of time t by v= gt.velocity is given as a function of time t by v= gt.
� Plot v as a function of t for 0 ≤ t≤ tf, where tf is the final time entered by the user.
13
![Page 14: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/14.jpg)
Script Files Script Files -- ExampleExample
% Comments section
% Program falling speed.m:
% Plots speed of a falling object.
% Created on March 1, 2004 by W. Palm
%
% Input Variable:% Input Variable:
% tf= final time (in seconds)
%
% Output Variables:
% t = array of times at which speed is
% computed (in seconds)
% v = array of speeds (meters/second)
14
![Page 15: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/15.jpg)
Script Files Script Files -- ExampleExample
% Parameter Value:
g = 9.81;
% Acceleration in SI units
% Input section:
tf = input(’Enter final time in seconds:’);
% Calculation section:% Calculation section:
dt= tf/500;
% Create an array of 501 time values.
t = [0:dt:tf];
% Compute speed values.
v = g*t;
% Output section:
Plot(t,v),xlabel(’t(s)’),ylabel(’vm/s)’)
15
![Page 16: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/16.jpg)
Notes on Script File NamesNotes on Script File Names
1. The name of a script file must begin with a letter, and may include digits and the underscore character, up to 31 characters.
2. Do not give a script file the same name as a 2. Do not give a script file the same name as a variable.
3. Do not give a script file the same name as a Matlab command or function. You can check to see if a command, function or file name already exists by using the exist command.
16
![Page 17: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/17.jpg)
Some Input/output CommandsSome Input/output Commands
Command Description
disp(A) Displays the contents, but not the name, of the array A.
disp(’text’) Displays the text string enclosed within quotes.
17
quotes.
x = input(’text’)
Displays the text in quotes, waits for user input from the keyboard, and stores the value in x.
x = input(’text’,’s’)
Displays the text in quotes, waits for user input from the keyboard, and stores the input as a string in x.
![Page 18: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/18.jpg)
UserUser--defined Functionsdefined Functions
� Another type of m-files.
� It is simply a script file that implements some operation that is not available in Matlab.
� It uses Matlab commands and accepts user arguments.
� To define your function, begin the script file with
function [output variables] = name(input variables)function [output variables] = name(input variables)
� Note:
◦ the output variables are enclosed in square brackets.
◦ the input variables must be enclosed with parentheses.
◦ The function name should be the same as the file name in which it is saved (with the .m extension).
18
![Page 19: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/19.jpg)
UserUser--defined Functions defined Functions -- ExampleExample� Example
function z = fun(x,y)
u = 3*x;
z = u + 6*y.^2;
� Call this function with its output argument:
>> z = fun(3,7)
z = 303z = 303
� The function uses x = 3 and y = 7 to compute z.
Note
• the use of a semicolon at the end of the lines prevents the values of u and z from being displayed.
• the use of the array exponentiation operator (.^). This enables the function to accept y as an array.
• the variables defined inside the function are local to the function and are cleared when the function returns 19
![Page 20: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/20.jpg)
Example of Function Definition Example of Function Definition LinesLines
1. One input, one output: function names in red letters
function [area_square] = square(side) square.m
2. Brackets are optional for one input, one output:
function area_square = square(side) square.mfunction area_square = square(side) square.m
3. Three inputs, one output:
function [volume_box] = box(height,width,length) box.m
4. One input, two outputs:
function [area_circle,circumf] = circle(radius) circle.m
5. No named output:
function sqplot(side) sqplot.m
20
![Page 21: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/21.jpg)
FunctionsFunctions-- Local VariablesLocal Variables
� The names of the input variables given in the function definition line are local to that function.
� This means that other variable names can be � This means that other variable names can be used when you call the function.
� All variables inside a function are erased after the function finishes executing, except when the same variable names appear in the output variable list used in the function call.
21
![Page 22: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/22.jpg)
Functions Functions –– Global VariablesGlobal Variables
� The global keyword declares certain variables global, and therefore their values are available to the basic workspace and to other functions that declare these variables global. declare these variables global.
� The syntax to declare the variables a, x, and q is global a x q
� Any assignment to those variables, in any function or in the base workspace, is available to all the other functions declaring them global.
22
![Page 23: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/23.jpg)
SubfunctionsSubfunctions
� Primary : the first function in an m-file and has the same name as the file name. used to call the function from the command line or from other m-file.
� Subfunctions : functions defined in the same file as the primary function and they are available to it only (except with function handles). Used to break large tasks into smaller oners
23
![Page 24: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/24.jpg)
SubfunctionsSubfunctions -- ExampleExample
% function to compute circle parameters
% Inputs: radius of the circle
% outputs:
% 1) area: area of circle
% 2) cricum: circumference of the circle% 2) cricum: circumference of the circle
% the function contains two subfunctions; computeArea and
% computeCircum to calculate the area and the circumference
% the given radius
24
![Page 25: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/25.jpg)
% main function
function [area,circum] = circleParameters(radius)
area = computeArea(radius) ;
circum = computeCircum(radius) ;
% function to compute the area
function a = computeArea(r)
SubfunctionsSubfunctions –– Example Cont’dExample Cont’d
function a = computeArea(r)
a = pi*r^2;
% function to compute circumference
function c = computeCircum(r)
c = 2*pi*r;
25
![Page 26: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/26.jpg)
Functions Handle @Functions Handle @
� It is used to call functions indirectly.
� The handle then can be used as an argument to other functions or as a new function that accepts argumentsfunction that accepts arguments
� For Matlab functions
fHanldle = @functionName
� For anonymous functions
fHandle = @ (argList) anonymus function
26
![Page 27: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/27.jpg)
Functions Handle @Functions Handle @
� Example 1 : creating handle for a Matlab function>> fhandle = @humps;>> x = fminbnd(fhandle, 0.3, 1)x =
0.6370
� Example 2: creating and using a handle to anonymous function� Example 2: creating and using a handle to anonymous function>> sqr = @(x) x.^2;>> a = sqr(5)a =
25>> quad(sqr, 0, 1)ans =
0.3333
27
![Page 28: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/28.jpg)
fzerofzero functionfunction
� Use fzero function to find the zero(s) of a function of single variable, denoted by x.
fzero(‘function’,x0)
� function is the function expression as a string.
� x0 is the initial guess of the solution.� x0 is the initial guess of the solution.
� For example, fzero(’cos’,2) returns the value 1.5708.
� The function fzero(‘function’,x0) tries to find a zero of function near x0, if x0 is a scalar. fzero(‘function’,[x1 x2] searches for the zero in the interval [x1,x2]. The value returned by fzero is near a point where function changes sign or NaN if the search fails.
28
![Page 29: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/29.jpg)
fminbndfminbnd functionfunction
� The fminbnd function finds the minimum of a function of a single variable, which is denoted by x.
� One form of its syntax is fminbnd (’function’, x1, x2) fminbnd (’function’, x1, x2)
where function is a string containing the expression to be minimized.
� The fminbnd function returns a value of x that minimizes the function in the interval x1 ≤x ≤x2. For example, fminbnd(’cos’,0,4) returns the value 3.1416.
29
![Page 30: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/30.jpg)
fminsearchfminsearch FunctionFunction
� The fminsearch function finds the minimum of a function of several variables, which is denoted by x.
� One form of its syntax is fminsearch(function, x0)
where function is a function handle for the function where function is a function handle for the function to be minimized and x0 is a vector for initial point.
� Example - find the minimum of f(x,y) = x*exp(-x2 –y2)
>> % define the function handle
>> f = @ (x) x(1)*exp(-(x(1))^2 – (x(2))^2)
>> fminsearch(f,[0,0])
ans = -0.7071 0.000
30
![Page 31: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/31.jpg)
Working with Data FilesWorking with Data Files
� Matlab has the capability of importing data created by other application into its workspace.
� Also, it is capable of exporting workspace � Also, it is capable of exporting workspace variables so that it can be used by other applications
31
![Page 32: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/32.jpg)
Importing & Exporting Importing & Exporting Spreadsheet FilesSpreadsheet Files
� The command
A = xlsread(’filename’)
imports the Microsoft Excel workbook file filename.xls into the array A.
� The command � The command
[A, B] = xlsread(’filename’)
imports all numeric data into the array A and all text data into the cell arrayB
� The command
[SUCCESS,MESSAGE]=xlswrite(FILE,ARRAY)
writes the ARRAY into and xls file whose name is given by FILE.
32
![Page 33: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/33.jpg)
Spreadsheet ExamplesSpreadsheet Examples>> [num,charc] =
xlsread(‘e1.xls’)
num =
1.3000 2.1000 29.0000
3.5000 9.0300 3.1000
0.1000 2.0330 2.1000
-2.0000 -0.2000 0.3000
22.0000 1.0000 0.5552
14.0000 - 123.0000 7.0000
Exa
mp
le 1
14.0000 - 123.0000 7.0000
charc =
'x' 'y' 'z'
33
e1.xls
>> a = [2 , 3 ; 4 , 5] ;
>> [succes,message] = xlswrite(‘e2.xls’,a)
succes =
1
message =
message: ''
identifier: ''
Exa
mp
le 2
![Page 34: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/34.jpg)
Working with CSV filesWorking with CSV files
� CSV stands for Comma-Separated Values
� One format that is used to exchange data between applications
� Some properties � Some properties ◦ Each record is a line
◦ Records are separated by a carriage return and a line feed pair.
◦ Record fields are separated by commas.
◦ leading and trailing spaces adjacent to commas are ignored.
34
![Page 35: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/35.jpg)
Working with CSV filesWorking with CSV files
� Commands to
◦ Read CSV data into matrix X
X = csvread (fileName)
◦Write matrix M into file fileName◦Write matrix M into file fileName
csvwrite(fileName,M)
>> x = csvread('csvExample.csv')
x =
1 3 10 20
-9 2 1 12
35
![Page 36: Computer Applications Lab Lab 4 Functions and Script Files · 2016-02-06 · Functions Functions – – Global VariablesGlobal Variables The global keyword declares certain variables](https://reader033.vdocuments.mx/reader033/viewer/2022050101/5f408434a92bdf502f0598ea/html5/thumbnails/36.jpg)
Working with ASCII FilesWorking with ASCII Files
� Many applications support the ASCII file format.
� If the ASCII file contains a header or the data is separated by commas , you have to remove the header and replace the commas with spaces (one at least); otherwise Matlab will produce an error message.
� To load the data in filename into matrix S
S = load(‘filename’)
� To save ASCII data
save filename A - ASCII
36