Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
st: nested loops with varying degrees of nesting
From
David Kantor <[email protected]>
To
Statalist <[email protected]>
Subject
st: nested loops with varying degrees of nesting
Date
Tue, 01 Oct 2013 18:04:49 -0400
Hello all,
I would like to write a program that involves nested loops, where the
degree of nesting is flexible.
Consider the following simplified shell of a program. c1, c2, c3 are
options that, for each one that is present, an additional a level of
looping should be invoked.
prog def t1
syntax , [c1 c2 c3]
if "`c1'" ~= "" {
local loop1 "forvalues d1 = 1/4 {"
local loop1end "}"
}
if "`c2'" ~= "" {
local loop2 "forvalues d2 = 1/4 {"
local loop2end "}"
}
if "`c3'" ~= "" {
local loop3 "forvalues d3 = 1/4 {"
local loop3end "}"
}
`loop1'
`loop2'
`loop3'
disp "`d1' `d2' `d3'"
`loop3end'
`loop2end'
`loop1end'
end
----
When this runs, with one or more of the c1,c2,c3 options, I get
unrecognized command: } invalid command name
--just the same as when I type
}
in the command window.
Evidently, a macro can stand for a command, but not "}" -- or "}" is
not a command..
Does anyone have an Idea of how to accomplish this goal? I do have
one idea, involving counting the number of loops:
if num_loops==1 {
forvalues d1 = 1/4 {
do_stuff
}
}
else if num_loops==2 {
forvalues d1 = 1/4 {
forvalues d2 = 1/4 {
do_stuff
}
}
else if num_loops==3 {
forvalues d1 = 1/4 {
forvalues d2 = 1/4 {
forvalues d3 = 1/4 {
do_stuff
}
}
}
}
-- but I'd rather do something more succinct, if possible; my actual
program may have up to 8 levels of nesting.
Does anyone have a suggestion?
(I do have another idea: build the entire nested looping command into
one macro; I have not tried this yet.)
I use Stata 10.
Thanks
--David
*
* For searches and help try:
* http://www.stata.com/help.cgi?search
* http://www.stata.com/support/faqs/resources/statalist-faq/
* http://www.ats.ucla.edu/stat/stata/