Search code examples
matlabnumerical-integration

Matlab monte carlo integration for loop


I'm trying to write function which calculates the integral using the Monte Carlo method in MATLAB. I'm not familiar enough with MATLAB to understand why I'm getting the issue of the integration being different each time. this is my code:

f=@(x)exp(-(x-3).^2);
N = 1000; %random samples 
a = 0; % lower bound 
b = 3; %upper bound

x2=linspace(0,3,1000);
syms z % zero vector holder to find max y value
z = zeros(size(x2));
z = f(x2);
y = f(b).*rand(1,1000);
x = a +(b-a)*rand(1,N);
count = 0;
for k=1:numel(x);
    %produce random x coordinate 
    if y(k) <= f(x);
        count= count +1;
    end
end
count;
i = (b-a)/N*sum(f(x));

When I run this, the i value changes each time but I want the integral to be calculated using the for loop. Thanks


Solution

  • Your i calculation at the end is wrong, it should be along the lines of

    count/numel(x) * max(z) * (b-a)