0
$\begingroup$

Say I have a piecewise function:

V[m_] := Piecewise[{{(1 + m)^2, m >= 1}, {Log[m], m < 1}}]

And I input a large list of m values, I get three lists output: The list of V[m] values, the list of m values for which m >= 1, and the list of m values for which m < 1.

I only require an output list of the V[m] values. How do I get rid of the other two lists?

Apologies if this is an obvious question! Any help would be greatly appreciated.

$\endgroup$
5
  • $\begingroup$ I am not understanding the issue here. V /@ {1, 10, 200, 0.1, 100} outputs {4, 121, 40401, -2.30259, 10201}. Is this not what you want? $\endgroup$
    – Mr.Wizard
    Commented Feb 18, 2017 at 10:49
  • $\begingroup$ Possible duplicate of How to select a certain portion of a piecewise function? $\endgroup$
    – zhk
    Commented Feb 18, 2017 at 10:49
  • 1
    $\begingroup$ Ah - many apologies. I was incorrectly calling the function V - thank you @Mr.Wizard for solving. $\endgroup$
    – emc3636
    Commented Feb 18, 2017 at 10:55
  • $\begingroup$ No problem. Glad I could help. :-) $\endgroup$
    – Mr.Wizard
    Commented Feb 18, 2017 at 11:00
  • $\begingroup$ You can have V evaluate lists the way you were expecting it to. See my answer below. $\endgroup$
    – m_goldberg
    Commented Feb 18, 2017 at 11:01

1 Answer 1

1
$\begingroup$

With the definition you have given, V isn't set up to thread over lists, which is what you seem to expect it to do. You can make that work that easy enough by giving it the Listable attribute.

SetAttributes[V, Listable]
V[m_] := Piecewise[{{(1 + m)^2, m >= 1}, {Log[m], m < 1}}]

SeedRandom[42]; data = RandomReal[4, 10]

{1.70362, 1.56409, 1.38828, 1.81496, 2.22385, 1.15668, 1.18739, 0.825631, 1.30068, 3.8933}

Now,

V[data]

gives

{7.30957, 6.57457, 5.70387, 7.92401, 10.3932, 4.65126, 4.78468, -0.191608, 5.29312, 23.9444}

It will still work as it did originally if given a single value.

V[10]

121

$\endgroup$

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