Message Boards Message Boards

0
|
5089 Views
|
2 Replies
|
2 Total Likes
View groups...
Share
Share this post:

Make a conditional statement work in a Loop?

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]; ]

POSTED BY: Maria Bustamante
2 Replies

Also,

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).

I hope this helps.

Regards

POSTED BY: Neil Singer
Posted 5 years ago

In if[j < 3, x = j, x = 0];

if should be If.

POSTED BY: Rohit Namjoshi
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract