MATLAB: Find inverse of a cdf so as to sample x

cdfcumtrapzcumulativecumulative distribution functiondistributionerfinvfinversepdfprobability distribution function

I have a cdf calculated as follows:
mu = 0;
var = 1;
x = -10:0.01:10;
y = cumtrapz((2*pi*(var))^(-0.5)* exp(-((x-mu).^2)/(2*(var))));
This gives the cdf of my probability distribution function (pdf): (2*pi*(var))^(-0.5)* exp(-((x-mu).^2)/(2*(var)))
But i want to sample the values of x randomly for this pdf. So I've created the cdf stored in variable y.
If i can find the inverse cdf, then i can uniformly select y values and then calculate using inverse cdf the corresponding x values that become my sample.
with the inverse function of the cdf, i want to get x in terms of y,
eg, y = F(x)
then x = Finverse(y)
like in figure:
Screen Shot 2019-09-22 at 10.57.04.png
I want to pass in y in the figure to Finverse(y) which is inverse of cdf, and then i can get x as:
x = Finverse(y)
But, i've tried many methods till now, but none seem to help.
i've tried to use :
i = erfinv(y)
but this gives me values as vector, but i need function so that i can pass in the values of y to get x. Please help.

Best Answer

As I suggested earlier in find finverse of cumtrapz():
If you want to use cumtrapz, the interp1 function is likely the best option:
mu = 0;
v = 1;
x = -7:0.01:7;
fx = cumtrapz(1/sqrt(2*pi*(v)) * exp(-((x-mu).^2)/(2*(v))));
y = [5 25 50 75 95];
fi = interp1(fx, x, y, 'linear','extrap')
figure
plot(x, fx)
hold on
plot(fi, y, '+')
hold off
grid
This plots ‘+’ markers at the appropriate values of the ‘y’ vector. I call the inverse ‘fi’. I had to restrict your original ‘x’ vector because with the original vector, the ‘fx’ points were not unique, as interp1 defines that.
Enlarging on that:
mu = 0;
v = 1;
x = -7:0.01:7;
fx = cumtrapz(1/sqrt(2*pi*(v)) * exp(-((x-mu).^2)/(2*(v))));
y = [5 25 50 75 95];
Finverse = @(y) interp1(fx, x, y, 'linear','extrap');
figure
plot(x, fx)
hold on
plot(Finverse(y), y, '+')
hold off
grid
That should do what you want.