I have a user defined function which takes multidimensional input, e.g a function that takes two algebraic variables a and b as well as a matrix m and computes some rule function as:

f[a_,b_,m_] := {a :> m[[1,1]]*a + m[[2,1]]*b, b :> m[[1,2]]*a + m[[2,2]]*b}

Now if I had a similar function over just single variables, e.g g[a,b,c,d] I could perform said function using the syntax g @@ vec where vec = {a,b,c,d}. What I would like achieve is something like:

v = {a,b}
m = {{p,q},{r,s}}
f @@ {v,m}

but doing so produces

f[{a, b}, {{p, q}, {r, s}}]

since the braces encompassing the {a,b} variable have been retained. This problem also occurs for the use of Slot, producing identical output for f[#1,#2] &[v,m] and even just f[#, m] &[v]. Neither Join[v,m] or Catenate[{v,m}] produce a useful list to apply.

How can pass a function a list and then a matrix and have it evaluated in the correct manner?


2 Answers 2


There are probably many ways to do this and here are just some examples to get you going into the right direction.

First note that you might simply use Sequence:

f[a_,b_,m_] := {a :> m[[1,1]]*a + m[[2,1]]*b, b :> m[[1,2]]*a + m[[2,2]]*b}

v = {a , b};
m = {{p,q},{r,s}};

f @@ { Sequence @@ v, m }


{a :> {{p, q}, {r, s}}[[1, 1]] a + {{p, q}, {r, s}}[[2, 1]] b,
 b :> {{p, q}, {r, s}}[[1, 2]] a + {{p, q}, {r, s}}[[2, 2]] b}

You might also add the vector as a special case to your function definition:

f[ {a_, b_}, m_] := {a :> m[[1,1]]*a + m[[2,1]]*b, b :> m[[1,2]]*a + m[[2,2]]*b}

Instead of naively trying Join[v,m] or Catenate[{v,m}], instead you must add an extra level to the matrix argument, using either:

(* or *)

which both produce the result

{a, b, {{p, q}, {r, s}}}

such that you can now use f @@ Join[v,{m}] to produce the desired output

{a :> a {{p, q}, {r, s}}[[1, 1]] + b {{p, q}, {r, s}}[[2, 1]], 
 b :> a {{p, q}, {r, s}}[[1, 2]] + b {{p, q}, {r, s}}[[2, 2]]}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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