Filter löschen
Filter löschen

Run single equation many times

1 Ansicht (letzte 30 Tage)
Luke Radcliff
Luke Radcliff am 28 Jun. 2016
Bearbeitet: Geoff Hayes am 29 Jun. 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.

Akzeptierte Antwort

Geoff Hayes
Geoff Hayes am 28 Jun. 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 Kommentar
Luke Radcliff
Luke Radcliff am 28 Jun. 2016
Bearbeitet: Geoff Hayes am 29 Jun. 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Walter Roberson
Walter Roberson am 28 Jun. 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 Kommentar
Luke Radcliff
Luke Radcliff am 28 Jun. 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.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by