Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Is it possible for the Piecewise function to process a vector comparison? For example, my input vector is

x={0,1,2,3,4}

I would like to define a function that gives me x^2 if x<3.5, and x+3 otherwise. i.e. I would like my output to be {0,1,4,9,7}. Here I define a function:

myfunc[x_] := Piecewise[{{x^2,x<3.5},{x+3,x>=3.5}}]

which obviously does not work. Is there a way to let Mathematica know that I want to compare x with 3.5 elementwise and apply that particular value to the segment as appropriate?

I'm used to R programming where I can use the ifelse function for this job, but I'm relatively new to Mathematica and don't know if this is possible.

Thanks!

share|improve this question
    
Related question: mathematica.stackexchange.com/questions/2821/… –  Leonid Shifrin Apr 1 '12 at 11:15
    
Thanks for your solutions; all work perfectly. As a R user I don't feel particularly comfortable with the way mathematica handles vector manipulation. Due to the nature of this problem I couldn't think of any keywords to search for a solution effectively. –  David L Apr 1 '12 at 16:53
1  
Note that solutions using Listable and Map lose the speed advantage offered by vectorized operations in Mathematica. If speed is important, you may wish to use things like UnitStep and Unitize instead. –  Leonid Shifrin Apr 1 '12 at 16:57
add comment

2 Answers

up vote 8 down vote accepted

I'm not in front of a computer now, but I think you should be able to set your function to Listable and use it as-is:

SetAttributes[myfunc, Listable]
share|improve this answer
1  
I am in front of a computer. It works. –  yohbs Apr 1 '12 at 12:48
    
@yohbs: Thanks! –  David Skulsky Apr 1 '12 at 18:41
add comment

There is nothing wrong with your function. You can Map it to a list as

 myfunc/@{0,1,2,3,4} 

you get your desired output.

Alternatively, you can use your myfunc to define a new function that accepts lists:

 mynewfunc[y_List] := Map[myfunc, y]

Now

 mynewfunc[{0,1,2,3,4}]

gives

 {0, 1, 4, 9, 7}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.