Netlogo: procedure with patches attributes as input variable

Viewed 31

i wonder if any netlogo expert can help me with the following: supposed my patches have 2 attributes (attr1 and attr2, say) and i need to compute a function of both attributes, as in this silly example

patches-own [ attr1 attr2]

to setup
  clear-all
  ask patches [set attr1 random 10]
  ask patches [set attr2 random 20]
  let mean-1 mean [attr1] of patches
  let mean-2 mean [attr2] of patches
  show mean-1
  show mean-2   
end

i would like to write a procedure which computes the mean (say) of any attribute i pass to it. something like:

  ask patches [set attr1 random 10]
  ask patches [set attr2 random 20]
  compute-mean attr1
  compute-mean attr2
end

to compute-mean #attr
  let mean-1 mean [#attr] of patches
  show mean-1
end

would anyone be able to help? thank you in advance

1 Answers

It would be a lot easier to compute-mean [attr1] of patches and not have to bother with extracting the values within your procedure. It also makes your procedure more flexible, allowing you to use it for subsets of patches. If you want a procedure to be a calculation, it is better to write it down as a reporter procedure using to-report. This way you can use the output it generates in other parts of your code as well instead of just showing it.

to go-1
  show compute-mean-1 [attr1] of patches
  show compute-mean-1 [attr2] of patches
end

to-report compute-mean-1 [#attr-list]
  let mean-1 mean #attr-list
  report mean-1
end

Now if you really just want to pass your procedure the name of the attribute and not the list of values, you will need to pass it the name of the attribute as a string and then use run-result to interpret that string ("attr1") as if it is a reporter (attr1)

to go-2
  show compute-mean-2 "attr1"
  show compute-mean-2 "attr2"
end

to-report compute-mean-2 [#attr-name]
  let mean-2 mean [run-result #attr-name] of patches
  report mean-2
end
Related