I tried to do Monte Carlo simulation in MATLAB, but it cannot be run! Can anyone help me?
1 回表示 (過去 30 日間)
古いコメントを表示
sigma=[2 1;1 3] %statr simulation with matlab
mu=[1,2]
N=100
counter=0
function w=mcs(x,y,z) %run the simulation
for i=1:N
x(i)=2*randn(1,N);
y(i)=randn(1,N);
z(i)= sqrt(1 - x.^2 - y.^2);
if w == x(i)*(x(i).^2 + y(i).^2 + Z(i).^2) %check if occur
counter=counter+1 %find the number of occurrence
plot3(x(i), y(i), z(i), '.r')
else
plot3(x(i), y(i), z(i), '.b')
end
end
histogram(w)
histfit(w)
PDFNormal=normpdf(x,mu,sigma)
plot(w,PDFNormal)
gm = gmdistribution(mu,sigma)
pdf(gm,x)
fsurf(@(x,y)reshape(pdf(gm,[x(:),y(:)]),size(x)),[-10 10])
disp(['The estimated value is ' num2str(Probability)])
end
0 件のコメント
回答 (2 件)
Walter Roberson
2022 年 5 月 22 日
You define a function but do not invoke the function.
The function does not have access to any of the variables you define before the function.
In order for the function to have access to those variables without passing them in, you would need to be using nested functions.
5 件のコメント
Walter Roberson
2022 年 5 月 23 日
Let us start with your w : your current code asks to output it, so logically it must not be a constant, but you have not given any formula for it.
My guess for the last thing I mentioned is
Probability = count ./ N;
Image Analyst
2022 年 5 月 22 日
編集済み: Image Analyst
2022 年 5 月 22 日
Try this:
sigma = [2 1; 1 3] %statr simulation with matlab
mu = [1, 2]
N = 100
w = mcs(N, mu) % Run the simulation
function w = mcs(N, mu) %run the simulation
% CODE
end
In the function, this will never work
if w == x(i)*(x(i).^2 + y(i).^2 + Z(i).^2) %check if occur
for two reasons. One, you have not yet defined w, and two, you're going a floating point comparison trying for an exact match. See the FAQ and use a tolerance instead
Finally, nowhere in the code do you compute (the badly-named) w. What the heck is it? You need a line of code that starts
w = something!!!
so that w will have a value. Otherwise there is nothing that the function can return.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Specifying Target for Graphics Output についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!