Bookmark and Share

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

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: st: Mata calls on Stata variables and macros

From   Maarten buis <>
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 --------------------------
input z 
scalar A = 1
scalar B = 2
scalar C = 3
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] = Re(cresult[i,j])

id_x1 = st_addvar("float","res1")

id_x2 = st_addvar("float","res2")

id_x3 = st_addvar("float","res3")
*------------------------ end example -----------------------

Hope this helps,

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


*   For searches and help try:

© Copyright 1996–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index