1

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?

gwr
  • 13,452
  • 2
  • 47
  • 78
Taiki Bessho
  • 886
  • 5
  • 15

1 Answers1

2

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:

  • There is an immediate assignment (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 OwnValue
  • The OwnValue for the Pattern might yet give good results for concrete values

Look 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. :)

gwr
  • 13,452
  • 2
  • 47
  • 78
  • As you know, I'm a beginner and not sure what you intended to say... Sorry, that's my problems. Anyway, to circumvent the error, is it a simple and natural way to use delayed set := to define? – Taiki Bessho Jul 02 '16 at 19:31
  • 1
    @Taki Bessho Yes, using := avoids the problem. You need to read about DownValues and OwnValues - it is essential. – gwr Jul 02 '16 at 20:07