Run single equation many times
조회 수: 1 (최근 30일)
이전 댓글 표시
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.
댓글 수: 0
채택된 답변
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개)
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!