# Implementation of a condition in a Function

I have defined that stoptime {5, 2, 10, 2, 1, 11, 11, 1, 5, 11}

and have the following function pvcosts = (-5/1.05^#) &[stoptime]

Now I want that everytime "stoptime" is 11, the function gets zero. I already thought about modifiying "stoptime", but I want it to stay the way it is.

How can I include a condition, that everytime "stoptime" is 11, "pvcosts" gets zero?

-
maybe pvcosts = If[# == 11, 0, (-5/1.05^#)] & /@ stoptime ? –  Pinguin Dirk Apr 21 '13 at 9:20
yes! thank you! –  Mary Apr 21 '13 at 9:26

Note that Power and Times have the attribute Listable, you can thus e.g. do:

x^# &[Range[10]]


or (the same)

Power[x, Range[10]]


to get:

{x, x^2, x^3, x^4, x^5, x^6, x^7, x^8, x^9, x^10}

Thus, you can apply your function pvccosts on stoptime directly.

In my suggestion (in the comments):

pvcosts = If[# == 11, 0, (-5/1.05^#)] & /@ stoptime


the function is not Listable (as If isn't), and thus I Map (a.k.a. /@ the function on stoptime.

We get:

{-3.91763, -4.53515, -3.06957, -4.53515, -4.7619, 0, 0, -4.7619, \ -3.91763, 0}

-

A general approach is to use the function Piecewise. You might define your function:

pv[x_] = Piecewise[{{0, x == 11}}, -5/1.05^x]


which says that if the input is 11, make the output 0, otherwise make it -5/1.05^x. You can call this with your stoptime

pv/@stoptime


which gives the answer you expect.

Another way to do this is to define the function

pvcost[x_] = -5/1.05^x

but then define an additional value (that at 11)

pvcost[11] = 0

Now, when you apply pvcost, it will evaluate using the formula. But whenever the specific value 11 is encountered, it will give output 0. The general rule about such things is that more specific definitions override the more generic.

-