Announcement

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

  • Mata Program which either works for a Mata matrix or for a Stata variable

    Dear Statalists,

    For an assignment I need to write a Mata program that recognises the kind of input and either runs the function for a Mata matrix or for the Stata variable that is specified in the function.

    Here you see the (simplified) program, that only works for Mata matrix:

    Code:
    clear mata
    mata  
    real matrix function posmean (real vector x) {    
            real vector A, B
            
            A = select(x, x[1,.]:>0)
            B = mean(A')                            
            return(B)
        }
        
    x1 = (1, 2, -3, 4, 5, -6)
    x2 = (1 \ 2 \ 3 \ -4 \ 4)
    posmean(x1)
    posmean(x2)
    }
    end

    Here you see the (simplified) program, that only works for Stata variable:

    Code:
    sysuse auto, clear
    clear mata
    mata:
    real matrix function posmean(transmorphic vector x) {
            real vector C, D
            
            st_view(L=.,.,x)
            C = select(L,L[.,.]:>0)
            D = mean(C)    
            return(D)
    }
    posmean("price")
    end
    Now I need one Mata program that either works for a Mata matrix or for a Stata variable. I tried several things but nothing worked. Therefore, I need your help!

    Thank you very much in advance!

    Best wishes
    Anika
    Last edited by Anika Bittner; 22 May 2020, 13:59.

  • #2
    As this is an assignment, I hint only at passing the function a name and then testing inside the function what exists. You don't say what should happen if both the variable and the matrix already exist.

    Comment


    • #3
      Dear Nick,

      Thank you for your answer! I tested the function with 'if (eltype(x)=="string"') and it works.
      Don't know if this is exactly what you meant but it serves its purpose.

      I feel really blessed that you answered my question. You kind of a hero for Stata!

      Best wishes
      Anika

      Comment

      Working...
      X