I tried to do Monte Carlo simulation in MATLAB, but it cannot be run! Can anyone help me?

조회 수: 2 (최근 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에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by