Can we use some patterns for the arguments of Part functions?
vec = Array[v,10];
rndmi = RandomInteger[100,10];
v[i_Integer] = rndmi[[i]]
Then I got a "Part::pspec" error.
Can we use some patterns for the arguments of Part functions or not?
Can we use some patterns for the arguments of Part functions?
vec = Array[v,10];
rndmi = RandomInteger[100,10];
v[i_Integer] = rndmi[[i]]
Then I got a "Part::pspec" error.
Can we use some patterns for the arguments of Part functions or not?
The quite ambiguous answer to your question is: "Yes, you (and we) can!". Sometimes we might simply let Mathematica complain or turn complaints off using Quiet...
So note this:
rndmi = RandomInteger[100,10]; (* immediately assigns a list of 10 numbers to rndmi *)
v[i_Integer] = Quiet @ rndmi[[ i ]]
{99, 93, 50, 56, 83, 40, 53, 62, 18, 90}[[i]]
That output tells you a great deal about why there has been a complaint, and also why it might still work:
Set) to the Pattern v[i_Integer] which leads to an error in the current case, since i is a symbol without an OwnValue (cf. OwnValues)rndmi never shows up, since it is immmediately replaced by its OwnValueOwnValue for the Pattern might yet give good results for concrete valuesLook at the definition for v:
?v
v[i_Integer]={99,93,50,56,83,40,53,62,18,90}[[i]]
And do try this:
v[1]
99
So, it does work but may not be the best choice for what you want. But again, Mathematica is rather a very logical tool. :)
:= avoids the problem. You need to read about DownValues and OwnValues - it is essential.
– gwr
Jul 02 '16 at 20:07
v[i_Integer] := rndmi[[i]]Understand the difference between Set (or =) and SetDelayed (or :=) – Kuba Jul 02 '16 at 09:57v[i_Integer] = rndmi[[i]]computesrndmi[[i]]first, exactly as you wrote it, with a symbolici, then assigns the result tov[i_Integer]. This will fail the same way as evaluatingrndmi[[i]]on its own would.v[i_Integer] := rndmi[[i]]makes the assignment without evaluatingrndmi[[i]]first. – Szabolcs Jul 02 '16 at 10:22