For[i = 1, i <= 20, i++,  
  f[x_, y_, z_] := 2 x + y + z;  
  data = RandomReal[{-1, 1}, {i, 3}];  
  mapping = Map[f @@ # &, data]  

In the above code, I want to run the loop 20 times, each time with different sets of random numbers, and finally print out the 20 values in the form of mapping [[i]]. Clearly I am not achieving that. Can anyone help me please?

  • $\begingroup$ missing ; before the last mapping, also, For does not return so you need Print. $\endgroup$
    – Kuba
    Jun 29 '17 at 12:10
  • $\begingroup$ Now about logic, each time you generate i rows, map every one but use only i-th, was that the goal? $\endgroup$
    – Kuba
    Jun 29 '17 at 12:11
  • 3
    $\begingroup$ Check Table[f @@ RandomReal[{-1, 1}, 3], 20] or f @@@ RandomReal[{-1, 1}, {20, 3}]. $\endgroup$
    – Kuba
    Jun 29 '17 at 12:12
f[x_, y_, z_] := 2 x + y + z;

You really don't want to use looping constructs to evaluate f over 20 sets of randoms arguments. Mathematica has better tools for doing that kind of thing.

The Table function is one first functions beginners should learn about, so I recommend Kuba'a suggestion:

SeedRandom[42]; m = Table[f @@ RandomReal[{-1, 1}, 3], 20];

A somewhat more advanced approach is (also mentioned by Kuba):

SeedRandom[42]; m = f @@@ RandomReal[{-1, 1}, {20, 3}];

In both cases

m // Column



Note: You can omit the expression SeedRandom[42]; in your work. It purpose here is to ensue the same result in both cases.


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.