%% Perform Monte Carlo Integration Using gpuArray-Enabled Functions
% This example shows how to use MATLAB functions and operators with gpuArray objects to compute the integral of a function by using the Monte Carlo integration method.
% Define the number of points to sample. Sample points in the domain of the function, the interval [-1,1] in both x and y coordinates, by creating random points with the rand function. To create a random array directly on the GPU, use the rand function and specify "gpuArray". For more information, see Establish Arrays on a GPU.

n = 1e6;
x = 2*rand(n,1,"gpuArray")-1;
y = 2*rand(n,1,"gpuArray")-1;

% Define the function to integrate, and use the Monte Carlo integration formula on it. This function approximates the value of \pi
%  by sampling points within the unit circle. Because the code uses gpuArray-enabled functions and operators on gpuArray objects, the computations automatically run on the GPU. You can perform binary operations such as element-wise multiplication using the same syntax that you use for MATLAB arrays. For more information about gpuArray-enabled functions, see Run MATLAB Functions on a GPU.

f = x.^2 + y.^2 <= 1;
result = 4*1/n*f*ones(n,1,"gpuArray")

% Copyright 2021 The MathWorks, Inc.