Announcement

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

  • Need help with Mata function

    Hello,

    I need help with this Mata task: Write a Mata function returning the sum of all odd elements of a vector (e.g. if the vector is x={1,2,4,7,5,6}, the function should return the solution of 1+4+5). The function should work for both column and row vectors (i.e. you need to use an if condition in your code). It is not necessary to embed this function in a Stata program. A simple Mata function for the use in Mata is sufficient.

    Is the following function correct:

    clear mata
    mata

    function task3(real vector x) {

    real scalar i
    real scalar n
    real scalar r
    real scalar c

    r = rows(x)
    c = cols(x)

    if (c == 1) {
    n = r
    X=J(1,1,.)
    }
    if (r == 1) {
    n = c
    Y=J(1,1,.)
    }
    for(i=1; i<=n; i = i + 2) {
    X = sum(i+i)
    Y = sum(i+i)
    }

    return(X)
    return(Y)
    }

    x = (1,2,4,7,5,6)
    task3(x)

    end


    Thanks,
    Ibrahim




  • #2
    You might get inspiration from:
    Code:
    : mata clear
    
    : function get_sum_odds(real rowvector x) return(mod(1..length(x), 2) * x')
    
    : x= 1,2,4,7,5,6
    
    : get_sum_odds(x)
      10
    I leave it to you to make the code handle both row and col vectors
    Kind regards

    nhb

    Comment


    • #3
      Dear Niels, Do you think my code is wrong?

      Comment


      • #4
        Not necessarily, I just thought you should use matrix notation to get what you wanted with less code
        Kind regards

        nhb

        Comment


        • #5
          Thank you.

          Comment

          Working...
          X