0

I am a physicist.

I have written a code on Monte Carlo simulation with condition loop.

I am getting some error in running this simulation code. I want to consider the positive value of the simulation result. When I run the code, I get an error.

I am running 10000 iterations and I have five parameters such as A,B,C,D and E. I am generating a random number for each parameter by using variance and mean of every parameter with the help of normal distribution.

The code is as follows:

    n = 10000;
    Constant = 5;
    Arand = (3*10^(12)*randn(1,n)) + 7*10^(6)*ones(1,n);
    Brand = (9*randn(1,n)) + 17*ones(1,n);
    Crand = (2*10^(-4)*randn(1,n)) + 0.2*ones(1,n);
    Drand = (0.0017*randn(1,n)) + 0.50*ones(1,n);
    Erand = (0.00004*randn(1,n)) + 1.5*ones(1,n);
    if P1 > 0
       P1 =  Constant*Arand.*Brand.*Crand.*Drand.*(1/Erand)
    end

    plot(P1);
Ansari
  • 8,168
  • 2
  • 23
  • 34
sus89
  • 1
  • 2
  • 1
    1) What is the problem with this code? 2) Where is `P1` initially defined? – Ansari May 09 '13 at 20:26
  • 2
    You have three errors here: `Erand = (` has a missing parenthesis, second: P1 has not been defined before the `if` and change `1/Erand` to `1./Erand` – R. Schifini May 09 '13 at 20:28
  • please note, that matlab understands scientific numbers format. You can write `2e-4` instead of `2*10^(-4)` – Serg May 09 '13 at 22:27

2 Answers2

0
P1 =  Constant*Arand.*Brand.*Crand.*Drand./Erand;

It's not clear what is P1 before the if statement.

Note, that "if P1 > 0" means "if all(P1 > 0)".

Serg
  • 13,470
  • 8
  • 36
  • 47
0

If you want to plot only those points where P1 is positive you need to change these lines:

if P1 > 0
   P1 =  Constant*Arand.*Brand.*Crand.*Drand.*(1/Erand)
end
plot(P1);

to the following:

Define P1:

P1 =  Constant*Arand.*Brand.*Crand.*Drand./Erand;

and then choose to plot only the positive values:

plot(P1(P1>0));

Hope this helps.

R. Schifini
  • 9,085
  • 2
  • 26
  • 32