3
$\begingroup$

I'm trying to enter a function in Mathematica that can take two inputs, a, and b, and return two outcomes based on those two numbers.

I will assume the name of this function as

Resultsf[a _,b _]

the inputs are :

x1=a; x2=b;

The two operations which I would like Mathematica to do are :

f1=x1+x2; f2=x1*x2;

Here are the two results that I anticipated from the function Resultsf[a _,b _]

input Resultsf[3,3] output 6

   9

what is the sequence of such kind of program? Regards

$\endgroup$
2
  • 2
    $\begingroup$ You can use List or {} to return multiple values. In your case it would be Resultsf[a_, b_] := {a+b, a*b}. $\endgroup$
    – Ben Izd
    Dec 28, 2022 at 5:51
  • 1
    $\begingroup$ As @BenIzd said, return a list, then you can display the list in any desired manner. For example, Results[3, 3] // Column or {Results[3, 3]} // Grid $\endgroup$
    – Bob Hanlon
    Dec 28, 2022 at 6:15

4 Answers 4

3
$\begingroup$

Using Apply and Function:

Resultsf[{a_, b_}] := Apply[Function[{x, y}, {x + y, x*y}], {a, b}]

Test using Syed's example:

Resultsf[#] & /@ {{-4, -1}, {-5, 2}, {-5, -5}, {3, 1}, {-5, -1}}
(*{{-5, 4}, {-3, -10}, {-10, 25}, {4, 3}, {-6, 5}}*)
$\endgroup$
1
$\begingroup$

The fundamental data structure in Mathematica is the List. If you want to put two things together, you put them into a list. So, Resultsf should probably return a list:

Resultsf[a_, b_] := {f1[a, b], f2[a, b]}

Try it out:

Resultsf[x, y]

{f1[x, y], f2[x, y]}

That's probably the easiest to understand way to do it. But there is a bit of repetition, specifically we had to "mention" a and b twice each. Mathematica has a built in function to deal with exactly this situation: multiple functions applied to the same arguments. It's called Through:

AlternateResultsf[a_, b_] := Through[{f1, f2}[a, b]]

Try this one out:

AlternateResultsf[x, y]

{f1[x, y], f2[x, y]}

To make this concrete, we'll use the multiplication and addition that you gave in your example:

AlternateResultsf[a_, b_] := Through[{Plus, Times}[a, b]]

And giving it a go:

AlternateResultsf[x, y]

{x + y, x y}

Or, going back to the first implementation:

Resultsf[a_, b_] := {a + b, a*b}

And now we have

Resultsf[x, y]

{x + y, x y}

$\endgroup$
1
$\begingroup$
Clear[alist]
SeedRandom[1];

alist = RandomInteger[{-5, 5}, {5, 2}]

{{-4, -1}, {-5, 2}, {-5, -5}, {3, 1}, {-5, -1}}

Through[{Plus, Times}[Sequence @@ #]] & /@ alist

OR

{Plus @@ #, Times @@ #} & /@ alist

Result:

{{-5, 4}, {-3, -10}, {-10, 25}, {4, 3}, {-6, 5}}

$\endgroup$
1
$\begingroup$

Using Query :

list = {{-4, -1}, {-5, 2}, {-5, -5}, {3, 1}, {-5, -1}};

Query[All, Apply /@ {Plus, Times}] @ list

{{-5, 4}, {-3, -10}, {-10, 25}, {4, 3}, {-6, 5}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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