I tried to do Monte Carlo simulation in MATLAB, but it cannot be run! Can anyone help me?
1 view (last 30 days)
Show older comments
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 Comments
Answers (2)
Walter Roberson
on 22 May 2022
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 Comments
Walter Roberson
on 23 May 2022
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
on 22 May 2022
Edited: Image Analyst
on 22 May 2022
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 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!