I am a beginner in running small simulations in Mathematica and I am trying to code a loop to compute the expected value of a piecewise function. To do so, I am trying first to make a conditional statement work inside a loop, without success.
I cannot make the conditional statement work inside the loop, which seems silly. In the code, the variable j can be either higher or lower than 3, but the output of the conditional statement in the code does not vary for different values of j. Can someone pinpoint the error? Thanks!
n=10;
For[z = 0; j = 1, j < n + 1, j++,
Print[j];
z = RandomVariate[NormalDistribution[0, 1], n];
if[j < 3, x = j, x = 0]; Print[x];
]
You never use z in your code. (I guess you are still building the code), however, you should almost never use For[] in Mathematica. Look at the getting started
The usual approach for replacing For is to operate on a list of numbers. Mathematica will be considerably faster and more powerful if you do that. Useful functions are Map[], and related functions. Also Nest and NestList will repeat operations. Many functions like RandomVariate will naturally produce a list of samples. (which can then be processed as a list and not used in a loop).