0
$\begingroup$

This question already has an answer here:

I have an array of elements and want to assign each element a specific value from a vector, at the same time I need the function ni[i] for the ith element of the list. I tried this, but it doesn't work:

Clear[nn, ni, m];
pop = {191202, 29234};
m = 2;
nn = Array[ni, m];
ni[i_] := pop[[i]]
ni[i]

During evaluation of In[834]:= Part::pkspec1: The expression i cannot
be used as a part specification. >>

Out[839]= {191202, 29234}[[i]]
$\endgroup$

marked as duplicate by MarcoB, m_goldberg, user9660, Jens, Yves Klett Jun 9 '16 at 8:58

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • $\begingroup$ With this definition, ni[1] and ni[2] are properly defined. But you can't use i because it doesn't have any value in the Part command [[ ]]. $\endgroup$ – bill s Jun 7 '16 at 21:02
  • 5
    $\begingroup$ Look at the solutions proposed in How to initialize downvalues from a list?, which appears to be an exact duplicate of your question; consider also that doing this will prevent you from using the rich machinery available in Mathematica to deal with lists natively, so it may not be a good idea. $\endgroup$ – MarcoB Jun 7 '16 at 23:13
1
$\begingroup$

Perhaps this will work for you.

Clear[nn, ni, m];
pop = {191202, 29234};
m = 2;
nn = Array[ni, m]

{ni[1], ni[2]}

Do[ni[i] = pop[[i]], {i, Length[pop]}];
nn

{191202, 29234}

$\endgroup$

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