3
$\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$
4
  • $\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
    Commented Nov 6, 2014 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
    Commented Nov 6, 2014 at 6:38
  • $\begingroup$ The problem is that aTemp[[3]] is a number. And you trying to assign value to a number. $\endgroup$
    – Acus
    Commented Nov 6, 2014 at 6:51
  • 1
    $\begingroup$ Answered in the "pitfalls" omnibus. Specifically see: (18393) Also related: (17767) $\endgroup$
    – Mr.Wizard
    Commented Nov 6, 2014 at 10:14

1 Answer 1

5
$\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$
1
  • $\begingroup$ +1 for posting an answer after finding your solution. $\endgroup$
    – Mr.Wizard
    Commented Nov 6, 2014 at 10:14

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