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

1 Ansicht (letzte 30 Tage)
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

Antworten (2)

Walter Roberson
Walter Roberson am 22 Mai 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 Kommentare
sogol bandekian
sogol bandekian am 23 Mai 2022
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 am 23 Mai 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;

Melden Sie sich an, um zu kommentieren.


Image Analyst
Image Analyst am 22 Mai 2022
Bearbeitet: Image Analyst am 22 Mai 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.

Kategorien

Mehr zu Specifying Target for Graphics Output finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by