Azzera filtri
Azzera filtri

Run single equation many times

1 visualizzazione (ultimi 30 giorni)
Luke Radcliff
Luke Radcliff il 28 Giu 2016
Modificato: Geoff Hayes il 29 Giu 2016
Here I have code that finds W over again 1000 times
nsample1 = 255;
nsample2 = 160;
X = 1.2 + 0.15*randn(1,nsample1);
Y = 1.1 + (1.25-1.1)*rand(1,nsample2);
B = [X Y];
c = 1e3;
for i = 1:c;
W(i+1,:) = 10*sum(B);
end
When I run the code it goes 1000 times, all outputs are the same. I want 1000 outputs that are nearly the same to eachother. X and Y using rand and randn to generate random numbers to get a different B each time, do I have something wrong in my for loop? Supposed to be like a monte carlo simulation.

Risposta accettata

Geoff Hayes
Geoff Hayes il 28 Giu 2016
Luke - on each iteration of the for loop, you are summing the same B that was initialized outside of the for loop
W(i+1,:) = 10*sum(B);
You will need to re-initialize B on each iteration of the loop in order to get new values. For example,
nsample1 = 255;
nsample2 = 160;
c = 1e3;
W = zeros(c,1);
for i = 1:c;
X = 1.2 + 0.15*randn(1,nsample1);
Y = 1.1 + (1.25-1.1)*rand(1,nsample2);
B = [X Y];
W(i+1,:) = 10*sum(B);
end
Note also how W is pre-sized outside of the loop. Try the above and see what happens!
  1 Commento
Luke Radcliff
Luke Radcliff il 28 Giu 2016
Modificato: Geoff Hayes il 29 Giu 2016
I see now, you have to put x y and b into the for loop so it re-randomizes the values every time, thank you.

Accedi per commentare.

Più risposte (1)

Walter Roberson
Walter Roberson il 28 Giu 2016
Your B is a vector. sum(B) is going to be a scalar. And you do the same sum(B) in each repetition of the loop. So all of the W elements are going to be the same, except W(1,:) which you do not store into.
I might have guessed that you want X+Y instead of sum([X,Y]) but your X and Y are different lengths, so I do not know what you are trying to calculate.
  1 Commento
Luke Radcliff
Luke Radcliff il 28 Giu 2016
okay so X and Y represent two different kinds of parts/pieces. The X piece is 1.2 lbs with a standard dev of 0.15 lb and there are 255 random pieces within that spec. Y piece is 1.1 lb to 1.25 lbs, there are 160 random pieces within that spec. W is the the total pallet weight, there are 10 boxes on the pallet. 1 X(255 pieces) and 1 Y(160 pieces) are in 1 box. I combined both vectors into 1 vector and took the sum and multiplied it by 10 to find the total weight of the pallet. Since the parts sizes are different everytime I run the code I want a different W for 1000 times, like a simulation.

Accedi per commentare.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by