2
$\begingroup$

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

$\endgroup$
  • $\begingroup$ initialPopulation[20, 10];(*A 20 by 10 list/array*) this does not create a 20 by 10 matrix. You need to use Table command to do that. $\endgroup$ – Nasser Nov 6 '14 at 2:40
  • $\begingroup$ Hi, I am sorry I should have been more clear here. This calls a function which creates a specified 20 by 10 list/array here. Best, Ben $\endgroup$ – ben18785 Nov 6 '14 at 6:38
  • $\begingroup$ The problem is that aTemp[[3]] is a number. And you trying to assign value to a number. $\endgroup$ – user18792 Nov 6 '14 at 6:51
  • 1
    $\begingroup$ Answered in the "pitfalls" omnibus. Specifically see: (18393) Also related: (17767) $\endgroup$ – Mr.Wizard Nov 6 '14 at 10:14
4
$\begingroup$

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

$\endgroup$
  • $\begingroup$ +1 for posting an answer after finding your solution. $\endgroup$ – Mr.Wizard Nov 6 '14 at 10:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.