Message Boards Message Boards

0
|
4084 Views
|
3 Replies
|
4 Total Likes
View groups...
Share
Share this post:

[?] Define Function using "Total[]"?

Posted 7 years ago

Using Mathematica 11, I want to define a piece wise function, using Total and Select, in the following way:

g[x_] := Total[Select[{
     {15, 4},
     {10, 2},
     {5, 3},
     {0, 1}
     }, #[[1]] < x &][[All, 2]]]

Unfortunately, g does not behave as i expect, for example

g[2]
g[12]
g[x]
g[x]/.{x->12}

returns

1
6
0
0

and not as expected

1
6
g[x]
6

I.e. when inserting numbers directly as an argument, the function works properly, but using a symbol as argument and assigning a value using a rule fails. This is not the case for any other function I define (e.g. using Piecewise). Is there a way to fix this, or is my method of defining a piece wise function unsuitable? Of course I could simply rewrite it using the Piecewise function, but I hope to get a deeper understanding of Mathematica mechanics investigating this problem.

Any ideas?

Thanks and regards, Moritz B

POSTED BY: M B
3 Replies
Posted 7 years ago

Thanks Carl Woll, that did the job! Also thanks for the explanation Sander Huisman!

POSTED BY: M B

Use

g[x_?NumberQ] := Total[Select[{
     {15, 4},
     {10, 2},
     {5, 3},
     {0, 1}
     }, #[[1]] < x &][[All, 2]]]

instead.

POSTED BY: Carl Woll

Select only picks elements for which the criterion evaluates to true. If is is unevaluated, or False it will not be selected. So if you do 'x', all the comparisons will not evaluate to true, but to left unevaluated. So therefore, Select will not pick anything and just return an empty list. The Total of an empty list is 0. This is normal behavior of Select:

Select[{{15, 4}, {10, 2}, {5, 3}, {0, 1}}, #[[1]] < x &]

returns {} because (first example):

15 < x

does not evaluate to True.

POSTED BY: Sander Huisman
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract