0
$\begingroup$

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

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

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}]
$\endgroup$
0
$\begingroup$

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

First set up your constants.

(* 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.

$\endgroup$
  • $\begingroup$ 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. $\endgroup$ – Edmund Feb 18 '15 at 16:12

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.