0

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]]
  • 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 [[ ]]. – bill s Jun 07 '16 at 21:02
  • 5
    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. – MarcoB Jun 07 '16 at 23:13

1 Answers1

1

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}

m_goldberg
  • 107,779
  • 16
  • 103
  • 257