Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Extracting restricted results from polyroots()

    I'm trying to find the real-valued x in (0,1) that solves this polynomial:
    \[ Nx^{N-1} - (N-1)x^N = y \] where y is in (0,1) and N is a given integer. I can get solutions using Mata's polyroots function for a given value of y:
    Code:
    mata
       c = -y, rangen(0, 0, N)', N, N-1
       polyroots(c)
    end
    But this gives me a bunch of complex solutions that fall outside my desired range. Is there a way to extract a certain restricted value from the solutions vector? I can of course look at the solutions and copy them directly, but I want to run this as part of an ado-file and so need a way to automate the process.

  • #2

    You can for example use select() in order to get the solutions which are real

    Code:
    s = polyroots(c)
    sReal = select(s,Im(s):==0)

    Comment


    • #3
      Thanks, I hadn't thought of that. Using your code produces a vector of complex numbers, so I needed to make it real and then apply the other restrictions one by one. This is what I ended up with:
      Code:
      s = polyroots(c)
      sReal = select(s, Im(s):==0)
      sReal = Re(sReal)
      sGeq0 = select(sReal, sReal[.,.]:>0)
      sLeq1 = select(sGeq0, sGeq0[.,.]:<1)
      solution = sLeq1
      I can then put this entry into a view matrix to export the results to a Stata variable. Problem solved!

      Comment


      • #4
        John Shannon I think you can save one line of code with
        Code:
        solution = select(sReal, sReal :> 0 :& sReal:<1)

        Comment

        Working...
        X