 Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.

Re: st: Mata calls on Stata variables and macros

 From Maarten buis To statalist@hsphsun2.harvard.edu Subject Re: st: Mata calls on Stata variables and macros Date Sun, 18 Apr 2010 08:32:31 +0000 (GMT)

--- On Sun, 18/4/10, Brad Jeffrey Hershbein wrote:
> I would like to solve a (cubic) polynomial equation where
> one of the coefficients of the polynomial is a variable in
> my dataset and the other coefficients are stored as scalars.
> That is, I want to solve for the roots of Ax^3 + Bx^2 + Cx +
> D = 0, where D is the variable Z in my dataset, and A, B,
> and C are stored in the scalars a1, b1, and c1,
> respectively. The values of A, B, C, and D are such that
> there is only one positive, real root in all cases, and I
> would like that root to be a new variable in the dataset.
>
> I know the Mata routine polyroots can find the roots of a
> polynomial, but I cannot figure out how to simultaneously
> pass the scalars and Z for polyroots to take as arguments,
> and how to return the positive real root as a new variable
> to Stata.

I am sure there are prettier solutions, but the example
below works.

*---------------------- begin example --------------------------
clear
input z
1
2
3
end
scalar A = 1
scalar B = 2
scalar C = 3
mata
d = st_data(.,"z")
a = st_numscalar("A")
b = st_numscalar("B")
c = st_numscalar("C")
result = J(rows(d),3,.)
cresult = C(result)
for(i=1; i<=rows(d);i++) {
coef = d[i], c, b, a
cresult[i,1..3] =polyroots(coef)
for(j=1; j<=cols(result);j++) {
if (Im(cresult[i,j])!=0) {
result[i,j]=.
}
else{
result[i,j] = Re(cresult[i,j])
}
}
}

st_store(.,id_x1,result[.,1])

st_store(.,id_x2,result[.,2])

st_store(.,id_x3,result[.,3])
end
*------------------------ end example -----------------------

Hope this helps,
Maarten

--------------------------
Maarten L. Buis
Institut fuer Soziologie
Universitaet Tuebingen
Wilhelmstrasse 36
72074 Tuebingen
Germany

http://www.maartenbuis.nl
--------------------------

*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/