# Defining a function that affects indices

I want to define a function, that works like this:

f[3v[1,2,3]] = 1/3 v[1,3,2] + 3^2 v[1,2,3]
f[2v[2,2,1]] = 1/2 v[2,1,2] + 2^2 v[2,2,1]


Basically, it should affect coefficients before vectors and also permute indices. I've tried to look through references but was confused. Can you help me with that?

Mathematica is great for this because you can use any pattern you like when defining a function. This can be used to pick out parts of interest from an expression and use them on the right-hand side to create a new one.

f[c_ v[arg1_, arg2_, arg3_]] := (1/c) v[arg1, arg3, arg2] + c^2 v[arg1, arg2, arg3]

f[3 v[1, 2, 3]]


9 v[1, 2, 3] + 1/3 v[1, 3, 2]

f[2 v[2, 2, 1]]


1/2 v[2, 1, 2] + 4 v[2, 2, 1]

• Can this work when i don't know in advance how many indices are there? Like here we have three indices, but suppose I also want the same function work when there are 4 indices? Like f[2 v [1,2,3,4]] = 1/2 v[1,3,2,4]+4 v[1,2,3,4] ? – Nicky Jan 23 at 18:29
• @Nicky rest in the pattern v[arg1_, arg2_, arg3_, rest___] matches zero or more parameters of v, perhaps that is what you need. Without knowing more about what you are trying to do it's hard to tell. – C. E. Jan 23 at 20:02
• Yes, you're right, I should've wrote exactly what I need. Basically, first I fix n - number of indices. I don't know in advance what it will be - 3, 7, or 14. I have linear combinations of vectors with n indices, like v[i_1, i_2, ..., v_n]. Now, I want to perform operations with these vectors and sometimes it involves swapping indices. Like f[k, v[i_1, i_2, ..., i_k, i_{k+1}, v_n]] = c[k] v[i_1, i_2, ..., i_{k+1}, i_k, ...., i_n]. – Nicky Jan 23 at 22:23