Nested foreach in NetLogo -


i trying calculate gini coefficient of set of numbers. gini coefficient half mean absolute difference. is, every possible pair of numbers in list, need take absolute difference , add these differences (and other stuff). code

to-report calc-gini [list-values]   let sumdiff 0   foreach list-values   [ foreach list-values     [ set sumdiff sumdiff + abs ( ?1 - ?2 )     ]   ]   report 0.5 * sumdiff / (mean list-values * (length list-values) ^ 2) end 

when test (eg show calc-gini (list 1 2 3)) error "task expected 2 inputs, got 1" on second foreach.

i think problem netlogo wants run through foreach loops simultaneously. if list length n, creates n pairs (that is, first item in list1 , first item in list2, second item in each list etc) requirement equal length lists comes from. need work n^2 pairs obtained crossing lists.

how can make nested foreach want and/or other primitive more appropriate?

netlogo doesn't have mechanism binding ?1 , ?2 outer , inner task. when sees ?1 , ?2 in code, expects both inputs come inner task. , since inner foreach provides 1 input, netlogo complains.

you can around problem assigning input of outer foreach local variable:

to-report calc-gini [list-values]   let sumdiff 0   foreach list-values   [ let v ?     foreach list-values     [ set sumdiff sumdiff + abs ( v - ? )     ]   ]   report 0.5 * sumdiff / (mean list-values * (length list-values) ^ 2) end 

that being said, here alternative implementation:

to-report calc-gini [ xs ]   report 0.5 * sum map [ sum-diff ? xs ] xs / (mean xs * (length xs) ^ 2) end  to-report sum-diff [ x xs ]   report sum map [ abs (x - ?) ] xs end 

Comments

Popular posts from this blog

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -

YouTubePlayerFragment cannot be cast to android.support.v4.app.Fragment -