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

回答(2 个)

Walter Roberson
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 个评论
sogol bandekian
sogol bandekian 2022-5-23
so with all of these I was wrong with writing these codes.how can I do the monte carlo similation other than examples in matlab??
Walter Roberson
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
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.

类别

Help CenterFile 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!

Translated by