# Table results within loops

I have the following code.

n = 0;
For[iii = 0, iii < Nn, iii++,

z = -L + iii*h;

While[
n < Nn - 1,
xn = -L + h*n;
result = result + func[z,xn];
n++;
]
(* Store (z, result *)
result = 0;
n = 0;
]


The function func is predefined and the constants Nn, h, L as well. My question is: how do I store the results obtained in the loop in a list? I would like to do this at the point where I commented "(* Store (z, result) )*". Ultimately I would like to use this list to make a listplot.

I have looked at previous questions where the answers almost always say that one should use 'reap' and 'saw', but I don't see how one should use this here, as I explicitly need to put result back to zero after each step

• Death to loops! :P [Seriously, the linked question has some suggestions for alternative approaches.] – Michael E2 Feb 18 '15 at 13:17
• Sow[result];result=0 of course using Table instead of For would be far better. – george2079 Feb 18 '15 at 13:20
• @george2079 I tried using a table but I just could not get it to work. – Funzies Feb 18 '15 at 13:24
• it should look like Table[result=0;While[];result,{iii,Nn}] – george2079 Feb 18 '15 at 14:54

You might want to try the following construct, which replaces the iterative code with Mathematica constructs and reduces the need for many of the variables:

Table[Sum[func[iii*h-L,h*n-L],{n,0,Nn-1}],{iii,0,Nn-1}]


Looking at this problem from a view of list you can do this the Mathematica way.

(* ClearAll["Global*"] *)
nSteps = 20;  h = 0.5; l = 2; (* Nn = nSteps and L = l, don't start with capitals *)


z and nx are just list that are combined a few times. Start by creating these list.

z = -l +#*h& /@ Range[0, nSteps-1, 1]
nx = -l+h*#& /@ Range[0, nSteps-2, 1]


Next we need a function that will do the action in the While. I don't know what your func does so I'm just going to make one that multiplies the z item across the nx list and Totals them up. You need the Totalpart but can make it do what you need inside instead of multiplying through.

func[x_Real, y_List] := Total[x*y]


You can check this works by picking the fist z and passing it into func with nx.

func[z[[1]],nx]


Now to get them all we can just Map the func across all the z items while pairing the z item with its result

{#,func[#,nx]}& /@ z


Hope this has helped.

• I just noticed you need a 0 step. In that case change to Range[0,nSteps,1] and Range[0,nSteps-1,1] to get the 0` step. I'll update the above. – Edmund Feb 18 '15 at 16:12