Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2010

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: piecewise function

  • To: mathgroup at smc.vnet.net
  • Subject: [mg109190] Re: piecewise function
  • From: Bill Rowe <readnews at sbcglobal.net>
  • Date: Fri, 16 Apr 2010 05:51:52 -0400 (EDT)

On 4/14/10 at 11:14 PM, mircea.darau at gmail.com (mircea) wrote:

>I want a define a piecewise constant function on an interval [a,b].
>What I did is:

>s[x_] := Module[{out}, out = 0;
>For[i = 1, i <= N, i++,
>If[mesh[[i]] <= x < mesh[[i + 1]],
>out = (mesh[[i]] + mesh[[i + 1]])/2; Break[]]]; out];

>where: mesh={x_1,x_2,..,x_{N+1} }, a=x_1<x_2<..<x_{N+1}=b

>However

>PiecewiseExpand /@ s[x]

>gives me 0.....

It appears to me there are two problems with your code. First,
there is a syntax problem. You should not use upper case letters
as variables. Specifically, N already has a built-in definition
which is inconsistent with its use as a variable. Since all
built-in Mathematica functions begin with an upper case letter,
if you refrain from using an upper case letter as the beginning
of anything you create, you avoid conflicts and will have better
success with Mathematica.

But I don't think fixing this will solve the problem. You doing
a comparison between subsequent values to determine which to
add. For the comparison to work, the elements of mesh must have
values assigned. But if that is the case, Mathematica's
evaluator will evaluate mesh[[i]]+meash[[i+1]]/2 to a value and
there will be nothing for PiecewiseExpand to expand.

=46inally, I it appears to me your out is simply a weighted sum of
the first values of mesh that are increasing. If I have this
correct, I would create that sum as follows:

Partition[First@Split[mesh, #2 >= #1&],2,1].{1,1/2}

or even better but perhaps less obvious

ListConvolve[{1/2<1},First@Split[mesh, #2 >= #1&]]

If the number if elements in mesh isn't too large, there won't
be any noticeable difference between you code (after correcting
the syntax problem) and my suggestions here. But once the number
of elements in mesh gets large using ListConvolve will be much
faster than anything you code using For.



  • Prev by Date: Re: ArrayPlot coordinates scaling for overlays
  • Next by Date: Re: ArrayPlot coordinates scaling for overlays
  • Previous by thread: Re: piecewise function
  • Next by thread: Re: piecewise function