Stata The Stata listserver
[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

Re: st: scalars in loops


From   Gary Longton <[email protected]>
To   [email protected]
Subject   Re: st: scalars in loops
Date   Tue, 15 Jun 2004 15:58:18 -0700

I believe the difference is that -which- takes an expression argument and -forvalues- does not. Though variables and scalars can be used in expressions, they cannot usually be used directly in non-expression arguments.

However, the introduction of of the macro expansion operator (in Stata 8 ?)

`=exp'

has made it easy to get around this, evaluating the expression, exp, and substituting a string result in its place.

eg. you could do this :

tempname m1
scalar `m1' = 5
forvalues a = 1(1)`=`m1'' {
di "`a'"
}

- Gary

Dimitriy V. Masterov wrote:


Can someone please explain to me why one cannot use scalars to define the
upper bound in a range of a forvalues loop. A forvalues loop with a local
works,  a while loop with a scalar works, a while loop with a local works,
but not a forvalues loop with a scalar. There seems to be nothing in the
programming manual about this issue.

This is the code for the examples above:

tempname m1 m2

scalar `m1'=5
local `m2'=5


forvalues a=1(1)``m2'' {
	di "`a'"
}

local a=1
	while `a'<=``m2'' {
		di "`a'"
	local a=`a'+1
}


local a=1
	while `a'<=`m1' {
		di "`a'"
	local a=`a'+1
}

forvalues a=1(1)`m1' {
	di "`a'"
}

I am using Stata 8.2 SE with XP.


*
*   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