3

I am trying to set part of a Doubly-indexed list aInitialPopulation to cNumHeg. Specifically I am trying to set the 3rd part of the list aInitialPopulatiom[[cNodeNumber]] to cNumHeg.

My (attempted) implementation is shown below, any help as to why it isn't working would be appreciated.

cNumNode = 10;
cNumHeg = 3;
aInitialPopulation = initialPopulation[20, 10];(*A user defined function which creates a 20 by 10 list/array*)
addHeg[aPopulation_, aNode_, aNumHeg_] := (aTemp = aPopulation[[aNode]]; aTemp[[3]] = aNumHeg; aPopulation[[aNode]] = aTemp);
addHeg[aInitialPopulation, cNumNode, cNumHeg]

When I do this I get an error of the form:

Set::setps: in the part assignment is not a symbol. 

It seems to be that I am trying to access part of a symbol rather than an array. I am not sure why this is - the code to modify the array works when it is not contained within a function definition. Any help much appreciated. Many thanks in advance.

Best,

Ben

ben18785
  • 3,167
  • 15
  • 28

1 Answers1

5

I have found the answer to my question. It is because I was trying to modify the value of x, rather than the name itself. A way round this is to make a copy of the variable, and operate on this. This below works:

addHeg[aPopulationImmutable_, aNode_, aNumHeg_] := Module[{aPopulation = aPopulationImmutable}, 
aPopulation[[aNode]][[3]] += aNumHeg; aPopulation]

Module here allows the variable aPopulation to be treated as local, and hence can be operated on.

Best,

Ben

ben18785
  • 3,167
  • 15
  • 28