Announcement

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

  • Check whether some Mata function exists?

    I've unsuccessfully searched for a nice way to check whether a Mata function exists in the user's Stata/Mata, and conditionally execute Mata code depending on that check. Although I can imagine various ways in which this need might arise, I've encountered it in the context of wanting to use the recently instituted undocumented built-in function vech_lower() if the user's Mata recognizes that function, and do the calculation another way if it does not. All I can think of is to try the function on some minimal valid argument and see what happens:
    Code:
    mata:
     // try to use vech_lower() with valid toy input and let Stata capture any error
    err = _stata("mata: vech__lower((1,1)\(1,1))",1)  
    if (err ==0 {
      // perform calculation using vech_lower()
     ...
    }
    else {
     // perform calculation some other way
    ...
    }
    end
    This seems clumsy, so I presume I'm just not finding some simple Mata function to check if some other function exists. This existence might or might not depend on the Stata version, so a call to stataversion() won't in general help here.

    Thanks, Mike

  • #2
    For functions that are not built-in, you should be able to use findexternal():

    Code:
    mata: findexternal("uniqrows()")

    Comment


    • #3
      Code:
      help mata which

      Comment


      • #4
        Thanks to both of you. I had seen mata which, but the fact that its results can only be trapped inside a Stata command made it less attractive to me. findexternal seems the more natural of the two alternatives to me here, but I'm open to correction:
        Code:
        found = (findexternal("somefunction()") != NULL)
        // vs
        found = (_stata("mata: mata which somefunction()",1) == 0)
        Regards, Mike
        Last edited by Mike Lacy; 14 Feb 2016, 13:22. Reason: Return code of 0 means "found"

        Comment


        • #5
          If you do not care about build in functions, then findexternal() is a fine solution.

          Comment


          • #6
            This existence might or might not depend on the Stata version, so a call to stataversion() won't in general help here.
            Keep in mind though that if it does depend on the Stata version then your Mata code needs to be compiled under the lowest version you intend to execute it. Say a function, cool_fcn(), exists in Stata 14, but not in Stata 13. Compiling your code in Stata 14 it will not work with Stata 13, regardless of the checks that you have in mind here. We have discussed this issue here.

            Best
            Daniel

            Comment

            Working...
            X