Statalist The Stata Listserver


[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

st: Help needed to understand behavior of Mata's increment/decrement operators


From   Joseph Coveney <[email protected]>
To   Statalist <[email protected]>
Subject   st: Help needed to understand behavior of Mata's increment/decrement operators
Date   Sun, 14 May 2006 19:55:51 +0900

Mata's documentation (in "[M-2] op_increment -- Increment and decrement
operators") says that increment and decrement operators are performed in
relation to the "entire expression."  I don't understand why the first and
second elements of -myrowvector = (i, i, ++i, i, i++, i)- don't come out the
same as the first element of -myrowvector = (i, ++i, i, i++, i)-.

Joseph Coveney

P.S.  The op_increment documentation does admonish, "and many programmers
feel that i++ or ++i should never be coded in a line that has a second
reference to i, before or after."  There's undoubtedly a painful story or
two behind that.  And I appreciate that Mata variables aren't Stata macros.
The examples are not intended to be realistic; they're just for exploration
of the operators' behavior in various contexts.

--------------

clear
set more off

local i = 1
display in smcl as result "`i'"
display in smcl as result "`++i'"
display in smcl as result "`i'"
display in smcl as result "`i++'"
display in smcl as result "`i'"

local i = 1
display in smcl as result "`i', `++i', `i', `i++', `i'"

local i = 1
matrix A = (`i', `++i', `i', `i++', `i')
matrix list A

mata
mata clear // -discard-
mata set matastrict on

real rowvector function incrementi(real scalar i)
{
    return(i, ++i, i, i++, i)
}

real rowvector function incrementj(real scalar j)
{
    return(j, j, ++j, j, j++, j)
}

real rowvector function incrementk(real scalar k)
{
    return( (k, ++k, k, k++, k) )
}

real rowvector function incrementl(real scalar l)
{
    return( (l, l, ++l, l, l++, l) )
}

real rowvector function incrementm(real scalar m)
{
    real rowvector temp; temp = J(1, 5, 0) // Sorry--old habits & all

    temp = (m, ++m, m, m++, m)
    return(temp)
}

real rowvector function incrementn(real scalar n)
{
    real rowvector temp; temp = J(1, 1, 0)

    temp = (n, n, ++n, n, n++, n)
    return(temp)
}

real rowvector function incremento(real scalar o)
{
    real rowvector temp; temp = J(1, 6, .z)

    temp[1] = o
    temp[2] = ++o
    temp[3] = o
    temp[4] = o++
    temp[5] = o

    return(temp)
}

incrementi(1)
incrementj(1)
incrementk(1)
incrementl(1)
incrementm(1)
incrementn(1)
incremento(1)

end

exit

------------

*
*   For searches and help try:
*   http://www.stata.com/support/faqs/res/findit.html
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/



© Copyright 1996–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index