Run single equation many times

2 ビュー (過去 30 日間)
Luke Radcliff 2016 年 6 月 28 日

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.

サインインしてコメントする。

採用された回答

Geoff Hayes 2016 年 6 月 28 日
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 件のコメント-1 件の古いコメントを表示-1 件の古いコメントを非表示
Luke Radcliff 2016 年 6 月 28 日

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.

サインインしてコメントする。

その他の回答 (1 件)

Walter Roberson 2016 年 6 月 28 日
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 件のコメント-1 件の古いコメントを表示-1 件の古いコメントを非表示
Luke Radcliff 2016 年 6 月 28 日
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.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by