Group Abstract Group Abstract

Message Boards Message Boards

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

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

Posted 9 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 9 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
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