-3

Here I hava a nested list as follow

a = {{1, 2, 3},{2, 1,2},{1, 3, 2}};

For[i = 1, i < Length[a], i++, t=Mean[a[[i]]]]

But the result is not expected I get 2 But I want {2,5/2,2}

Ahmed
  • 369
  • 1
  • 6
  • I want to use loop and put results in list this is what @tueda solution does. If you must use a loop, you can do First@Last@Reap[Do[Sow[Mean[a[[n]]]],{n,1,Length@a}]] but I think Map[Mean,a] is much better and more clear. (which is another way to write Mean /@ a. The reason your loop did not work is because you were overwriting t each time in the loop, and only the last value of t survived. – Nasser Sep 06 '22 at 06:59
  • Very down to earth way of doing it (wrong from the point of view of MMA coding) t = {}; For[i = 1, i <= Length[a], i++, AppendTo[t, Mean[a[[i]]]] ] – Daniele Binosi Sep 06 '22 at 07:11
  • thanks more Daniel Binosi – Ahmed Sep 06 '22 at 07:21

2 Answers2

5

Rule number one of WL: forget that For exists. It's never a good way to do things in Mathamatica. This is what you want to do:

a = {{1, 2, 3},{2, 1,2},{1, 3, 2}};
t = Map[Mean, a];

t

{2, 5/3, 2}

If you want a more general method for computing the mean of rows/columns, look at ArrayReduce:

ArrayReduce[Mean, a, 1] (* average over rows, giving you column means *)
ArrayReduce[Mean, a, 2] (* average over columns, giving you row means *)

{4/3, 2, 7/3}

{2, 5/3, 2}

Sjoerd Smit
  • 23,370
  • 46
  • 75
2

Do you mean you want {2,5/3,2}? This can be obtained by Mean /@ a.

tueda
  • 793
  • 3
  • 6