Monte Carlo Integration Method: How to iterate through matrix

I'm trying to use monte carlo method to find the area under the curve, e^x +1. Using monte carlo's method, I have successfully produced random points but I don't know how to test whether those points are inside the curve or not. Here's what I tried,
function [integral_dx] = integral_dx( f,a,b )
%integrate function (f) using monte carlo method
x2=linspace(a,b,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 = rand(1,1000);
h=0; % counters
n= 0;
%if you want to see visual representation just un-commnet plot lines
%plot(x2,z); hold on;
%plot(x,y,'x')
count = 0;
for k=1:numel(x);
for i = 1:x(k);
x=x(k);
y = y(k);
if y <= exp(x)+1;
count= count +1;
end
end
end
count
integral_dx = count/numel(x) * max(z) * (b-a);
end
But it isn't working. The problem is within the loop or rather, with the loop itself but I can't find out the issue. Please let me know if you can see any issues.

1 Comment

Alright, that's the second time I solved it by myself moments after resorting to this website. Using
function [integral_dx] = integral_dx( f,a,b )
%integrate function (f) using monte carlo method
x2=linspace(a,b,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 = rand(1,1000);
h=0; % counters
n= 0;
%if you want to see visual representation just un-commnet plot lines
plot(x2,z); hold on;
plot(x,y,'x')
count = 0;
for k=1:numel(x);
if y(k) <= exp(x(k))+1;
count= count +1;
end
end
count
integral_dx = count/numel(x) * max(z) * (b-a);
end
works. If you can offer any improvement that would be appreciated.

Sign in to comment.

Answers (0)

Asked:

on 12 Oct 2015

Community Treasure Hunt

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

Start Hunting!