0
$\begingroup$

I have a function f[a_, b_]: = b^a + a b. a takes values {1,2,3,4}, and b - {10,11,12}.

How is it better to calculate all values? Grid-type output.

Also, for every b I need to calculate values of function from all a and then take an average. As a result of such computing I would like to have 2 numbers for every b:

{b1, 1/4 (f[a1,b1)+f[a2,b1)+f[a3,b1)+f[a4,b1)} (basically {b, average f for all a})

What is the shortest way to do that? Can I do this without loops?

$\endgroup$
  • $\begingroup$ the first part of your question needs clarification. If you want all permutations of a+b from the two lists then Outer[Plus, {1, 2, 3, 4}, {10, 11, 12}] is somewhere to start but maybe best to show what output you want from first part of the question $\endgroup$ – Mike Honeychurch Nov 14 '15 at 4:52
  • $\begingroup$ @MikeHoneychurch I have much more complicated function and a and b just parts. So, basically,it's not a sum of two values a and b. $\endgroup$ – Maria Nov 14 '15 at 4:55
  • $\begingroup$ given the two example lists you have provided what output do you seek? You need to explain what you mean by "all values" $\endgroup$ – Mike Honeychurch Nov 14 '15 at 4:55
  • $\begingroup$ Value of function in each point (for every a and b) with values of particular a and b. Grid-type output. $\endgroup$ – Maria Nov 14 '15 at 4:59
  • $\begingroup$ in that case i think my answer addresses your question $\endgroup$ – Mike Honeychurch Nov 14 '15 at 5:01
2
$\begingroup$
a = {1, 2, 3, 4};
b = {10, 11, 12};

To get all the values:

vals = Outer[#2^#1 + #1*#2 &, a, b]
(* {{20, 22, 24}, {120, 143, 168}, {1030, 1364, 1764}, {10040, 14685, 20784}} *)

To get the averages:

vals = Outer[#2^#1 + #1*#2 &, a, b];
Transpose[{b, Mean[vals]}]
(* {{10, 5605/2}, {11, 8107/2}, {12, 5685}} *)

To see what is happening, evaluate

Clear[x, y, a, b, vals, f]
a = Array[x, 4]; b = Array[y, 3]
vals = Outer[f, a, b]
Transpose[{b, Mean[vals]}]
$\endgroup$
  • $\begingroup$ Will it work if function is very complicated and after that I plug in a I do numeric inverse Laplace transform for every b? can I still use Outer function? $\endgroup$ – Maria Nov 14 '15 at 5:07
  • $\begingroup$ @Maria. I don't really understand your question. The inverse Laplace transform of what? of a? In any case, Outer requires the list of a and b to be pre-determined. If you can define a function f[a_, b_] := ... that takes an element of a and an element of b and does something to it, no matter how complicated, this should work. $\endgroup$ – march Nov 14 '15 at 5:14
3
$\begingroup$

For the second part:

{#, Mean@Thread[f[a, #]]} & /@ b

(* {{10, 5605/2}, {11, 8107/2}, {12, 5685}} *)

For the first part:

Outer[f, a, b]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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