SUNY Geneseo Department of Mathematics
Friday, March 3
Math 230 02
Spring 2017
Prof. Doug Baldwin
Definition: a function with different definitions for different non-overlapping parts of its domain, together covering the whole domain.
Piecewise function definitions usually translate very easily into programming language “if” statements.
Example: absolute value
Try coding this in Matlab.
function [ absX ] = absoluteValue( x )
%ABSOLUTEVALUE. Find the absolute value of x.
if x >= 0
absX = x
else
absX = -x
end
end
Notice how each “arm” of the “if” is a straightforward translation into Matlab of the corresponding case in the piecewise definition.
Try the absolute value function...
>> absoluteValue( -22 )
absX =
22
ans =
22
>> absoluteValue( 2 )
absX =
2
ans =
2
Fibonacci Numbers: Give a piecewise definition for the Fibonacci numbers.
Definition
Try coding it in Matlab.
function [ F ] = fibonacci( n )
%FIBONACCI. Compute the n-th Fibonacci number.
if n > 1
F = fibonacci( n-1 ) + fibonacci( n-2 );
elseif n == 1
F = 1;
else
F = 0;
end
end
Some examples of it running...
>> fibonacci( 0 )
ans =
0
>> fibonacci( 1 )
ans =
1
>> fibonacci( 2 )
ans =
1
>> fibonacci( 3 )
ans =
2
>> fibonacci( 4 )
ans =
3
>> fibonacci( 5 )
ans =
5
Notice that this function was also a straightforward translation of the piecewise definition into Matlab, even including the places where the mathematical definition referred to other values of the function being defined (something called “recursion” or a “recursive definition”).
See the handout for details.
Work on lab (I’ll also bring an extra credit extension to it).