Announcement

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

  • If loop in Mata

    Hey I want to write a Mata function with an if condition
    function sum {
    sum(x)
    if sum(x) == 0 {
    sum(y)

    is that possible?

  • #2
    Yes. It's possible. Here's one possibility.

    .ÿversionÿ14.1

    .ÿ
    .ÿclearÿ*

    .ÿsetÿmoreÿoff

    .ÿ
    .ÿlocalÿlinesizeÿ`c(linesize)'

    .ÿsetÿlinesizeÿ78

    .ÿ
    .ÿmata:
    -------------------------------------------------ÿmataÿ(typeÿendÿtoÿexit)ÿ----
    :ÿmataÿsetÿmatastrictÿon

    :ÿ
    :ÿrealÿscalarÿfunctionÿsumif(realÿvectorÿX,ÿrealÿvectorÿY)ÿ{
    >ÿÿÿÿÿÿÿÿÿrealÿscalarÿresult
    >ÿÿÿÿÿÿÿÿÿresultÿ=ÿsum(X)
    >ÿÿÿÿÿÿÿÿÿifÿ(resultÿ==ÿ0)ÿreturn(sum(Y))
    >ÿÿÿÿÿÿÿÿÿelseÿreturn(result)
    >ÿ}

    :ÿ
    :ÿXÿ=ÿ(1,ÿ2,ÿ3)

    :ÿYÿ=ÿ(4,ÿ5,ÿ6)

    :ÿsumif(X,ÿY)
    ÿÿ6

    :ÿ
    :ÿXÿ=ÿ(0,ÿ0,ÿ0)

    :ÿsumif(X,ÿY)
    ÿÿ15

    :ÿ
    :ÿend
    ------------------------------------------------------------------------------

    .ÿ
    .ÿsetÿlinesizeÿ`linesize'

    .ÿ
    .ÿexit

    endÿofÿdo-file


    .

    Comment


    • #3
      It's not clear to me that you need a function for this. Consider

      Code:
      . mata
      ------------------------------------------------- mata (type end to exit) -
      : x = (0,0,0)
      
      : y = (1,2,3)
      
      : result = sum(x) == 0 ? sum(y) : sum(x)
      
      : result
        6
      If you are determined to have a function, it can written just about as concisely:

      Code:
       real myresult (real vector X, real vector Y) { 
           return(sum(X) == 0? sum(Y) : sum (X)) 
      } 
      
      myresult(x, y) 
        6
      Last edited by Nick Cox; 03 Jul 2016, 04:56.

      Comment


      • #4
        Thanks! solved the problem!

        Comment

        Working...
        X