Announcement

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

  • Calculating differences between adjacent elements

    Dear all,
    I wonder if there is any easy solution available in Mata for calculating the difference between adjacent elements of a (column) vector? For example, the difference of vector Y should return (Y[2]-Y[1], Y[3]-Y[2], ..., Y[n]-Y[n-1]).
    Thank you,
    Eilya.

  • #2
    Try:
    Code:
    . mata
    : y = 1::10
    : R = rows(y)
    : y[2..R] - y[1..(R-1)]
           1
        +-----+
      1 |  1  |
      2 |  1  |
      3 |  1  |
      4 |  1  |
      5 |  1  |
      6 |  1  |
      7 |  1  |
      8 |  1  |
      9 |  1  |
        +-----+
    : end
    Kind regards

    nhb

    Comment


    • #3
      Thanks for this, Niels. Works perfectly.

      Since I had to calculate the difference many times, I defined a simple function based on what you suggested. While it is simple, it may be worth it to consider including this for the future development of Mata language - for example, Matlab has this built in function.

      Best regards,
      Eilya.

      Comment

      Working...
      X