Code covered by the BSD License  

Highlights from
Piecewise defined function builder

4.66667

4.7 | 3 ratings Rate this file 17 Downloads (last 30 days) File Size: 2.59 KB File ID: #15851

Piecewise defined function builder

by Toby Driscoll

 

06 Aug 2007 (Updated 21 Aug 2007)

Constructs a callable function that applies different definitions based on supplied conditions.

| Watch this File

File Information
Description

F = PIECEWISE(COND1,DEFN1,...CONDn,DEFNn,DEFAULT) returns a callable
function F that applies different definitions according to supplied
conditions. For a given X, F(X) will test COND1 and apply DEFN1 if true,
etc. If all conditions fail, then DEFAULT is applied. For any particular
input, the first condition to match is the only one applied.

Each condition should be either a:
  * function handle evaluating to logical values, or
  * vector [a b] representing membership in the half-open interval [a,b).
Each definition should be either a:
  * function handle, or
  * scalar value.
The DEFAULT definition is optional; if omitted, it will be set to NaN.
  
All function definitions can accept multiple input variables, but they
all must accept the same number as in the call to F. They also should
all be vectorized, returning results the same size and shape as their
inputs. Complex inputs will work if the definitions are set up
accordingly; in that case, intervals will be tested using only Re parts.

The special syntax F() displays all the conditions and definitions for F.

Examples:
   f = piecewise([-1 1],@(x) 1+cos(pi*x),0); % a "cosine bell"
   ezplot(f,[-2 2])
   g = piecewise(@(x) sin(x)<0.5,@sin,@(x) 1-sin(x));
   ezplot(g,[-2*pi 2*pi])
   h = piecewise(@(x,y) (x<0)|(y<0),@(x,y) sin(x-y)); % defined on L
   ezsurf(h,[-1 1])
   chi = piecewise(@(x,y,z) x.^2+y.^2+z.^2<1,1,0); % characteristic func
   [ triplequad(chi,-1,1,-1,1,-1,1), 4/3*pi ]
       ans =
              4.1888 4.1888

MATLAB release MATLAB 7.4 (R2007a)
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Comments and Ratings (3)
21 Jun 2008 Swaminathan Padmanabhan

A useful functionality for many simulations.

01 Jul 2008 rob bie

found this exactly when i needed it, thanks

08 Oct 2011 Maurizio De Pitta'  
Please login to add a comment or rating.
Updates
21 Aug 2007

Improved documentation on overlapping definitions and on complex inputs.

Tag Activity for this File
Tag Applied By Date/Time
piecewise function Toby Driscoll 22 Oct 2008 09:22:17
piecewise function Ural Uluer 02 Nov 2008 08:24:31
piecewise function John 10 Feb 2010 17:43:00
piecewise function Marcel 18 Jul 2011 11:58:19
piecewise function VABAV 15 Jan 2012 13:52:03

Contact us at files@mathworks.com