1

I'm trying to generate a 2-by-6 matrix of random numbers based on their density function, for example

f(x)= 2x-4 for 2 < x < 3; 0 otherwise

So from what I understand I have to find the cumulative density function first, x2-4x, and then I have to invert it so that I can use the rand function.

This is that part I do not understand, how do I get the inverted function

Annylowell
  • 57
  • 4

1 Answers1

0

Try something similar to this method: https://stackoverflow.com/a/13914141/1011724.

However, your PDF is continuous so you need to adjust it slightly. The cumsum part becomes your CDF and the sum(r >= ... part becomes a definite integral from 0 to rand (which is just your CDF since it evaluates to 0 at x==0) so (ignoring your limits) you get

X = @(x)x.^2 - 4x 

To generate a random matrix go X(rand(2,6))

To account for your limits you can just multiply the entire function by x > 2 & x < 3 but also if it's greater than 3 then although the PDF is 0, the CDF should still be 32 - 4 =5

X_limited = @(x)(x.^2 - 4x ).*(x > 2 & x < 3) + (x>=3)*5

If you plot a graph of (x > 2 & x < 3) you will see it is a rectangular function between 2 and 3 and so multiplying by it makes anything outside of that window 0 but leaves anything inside the window unchanged. Similarly, x >= 3 is a step function start at x == 3 and thus it adds 5 to any values higher than 3 and since the windowing function will make sure the first term is zero when x is greater then 3, this step function ensures a value of 5 for all x greater than 3.

Now you just need to generate random numbers in whatever your range is. Assuming it's between 0 and 5

x = rand(2,6)*5
X_limited(x)
Community
  • 1
  • 1
Dan
  • 45,079
  • 17
  • 88
  • 157