Bookmark and Share

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]

Re: st: combination of k elements each being 0 or 1


From   Fernando Rios Avila <[email protected]>
To   [email protected]
Subject   Re: st: combination of k elements each being 0 or 1
Date   Tue, 4 Mar 2014 13:30:45 -0500

Hi Gregorio,
I do have a suggestion for the generalization of your algorithm. What
you are doing can be thought as the transformation from a number from
base 10 to base 2
It could go something like: (using your base code).
clear
local x 8
local n=2^`x'
set obs `n'
gen v0=""
forvalues i=1/`n' {
local n2=`i'-1
inbase 2 `n2'
return list
replace v0=r(base) in `i'
}

destring v0, replace

forvalues i=1/`x' {
gen v`i'=mod(v0,10)
replace v0=int(v0/10)
}

HTH
Fernando

On Tue, Mar 4, 2014 at 12:48 PM, Impavido, Gregorio <[email protected]> wrote:
> Hello.
>
> I would like to define a matrix (2^k x k) with all possible combinations of k elements each being 0 or 1.  The code below produces what I want for k = 5 and can be modified for different values of k. My questions are:
>
> - Is there a matrix function in STATA or MATA that generalizes the code below for variable k?
> - If not, does anybody have suggestions on how to generalize the loop for variable k?
>
> Thank you in advance for your help
> Gregorio
>
>
>
> ******* begin example
> clear
> set more off
> local x 5
>
> local n = 2^`x'
> set obs `n'
>
> forvalues i = 1/`x' {
> gen v`i' = .
> }
>
> * set trace on
> local j = 1
> while `j' < `n' {
> forvalues i1 = 0/1 {
>         forvalues i2 = 0/1 {
>                 forvalues i3 = 0/1 {
>                         forvalues i4 = 0/1 {
>                                 forvalues i5 = 0/1 {
>                                         forvalues l = 1/`x' {
>                                                 replace v`l' = `i`l'' in `j'
>                                                 }
>                                                 local j = `j' + 1
>                                         }
>                                 }
>                         }
>                 }
>         }
> }
> ******* end example
>
> *
> *   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/
*
*   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/


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