Download presentation
Presentation is loading. Please wait.
1
CIS 101: Computer Programming and Problem Solving Lecture 5 Usman Roshan Department of Computer Science NJIT
2
Function files Function File Input data Output
3
Function syntax function [output arguments] = function_name(input arguments) Example functions: function [A] = RectArea(x, y) function [V, S] = SphereVolArea(r)
4
Local and global variables So far ALL variables we have worked with have been global. This means they can be accessed and modified by any part of the program In functions variables are local by default (and global if they are defined as such)
5
Memory space Global memory space accessible by all scripts and functions Local space for function A Local space for function B
6
Defining and calling a function A function file must be saved before it can be used. The name of the file must be the same as the function name Examples: –FunctionFilename –function [A] = RectArea(x,y)RecArea.m –function[V, S] = SphereVolArea(r) SphereVolArea.m
7
Function for computing area of sphere
8
Area of sphere It won’t run if you click on the run button
9
Area of sphere The function is called from the command line…
10
Area of sphere Or the function can be called from a script.
11
Area of sphere Function output from script
12
Comparison between functions and scripts Both scripts and funtion files are saved with.m extension The first line in a function file is the definition line Function variables are local whereas script ones are global Function files can accept data through input arguments and can return data similarly When a function file is saved, the name of the file should be the same as the function’s.
13
Inline functions name = inline(‘math expression typed as a string’) name = inline(‘math expression’, arg1, …, argn) For example, double = inline(‘2*x’) defines a function that doubles the input. So double(10) = 20
14
Using inline to define area of sphere
15
Logical operators AND: if both are true result is true (1) OR: if either is true result is true (1) NOT: produces opposite of operand
16
Conditional statements if else end
17
Max of two numbers
19
Loops for k = f:s:t … end
20
Loops
22
while … end
23
Loops
25
Nested loops for k = 1:n for h = 1:m … end
26
Loops
28
break: terminates execution of loop continue: goes to next iteration of loop for k = 1:2:200 … continue … end stops execution and goes to next iteration
29
Loops break: terminates execution of loop continue: goes to next iteration of loop for k = 1:2:200 … break … end stops execution and exits loop
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.