1
$\begingroup$

I have a vector $A=\{1,2,3,4,5,6\}$, and I want to define a function of $A$ as

f[A_]:=A.X 

where $X$ is another vector. I want to define this function without fully specifying the components of $A$, but Mathematica does not recognize this, so I have to write

f[A1_,A2_,A3_,A4_,_A5_,A6_]:= {A1,A2,A3,A4,A5,A6}.X

where $Ai, i=1,...,6$ are equal to 1 to 6, respectively. The second method is not very convenient. So, I was wondering how I can use my first code so that Mathematica recognizes that. Many thanks!

It should be noted that this is not a duplicate of Can a function be made to accept a variable amount of inputs?, because the question you referred to asked about "how to accommodate varying number of inputs in a function", however, my question is about how to change the representation of vector (based on its fixed components) in a function.

$\endgroup$
  • $\begingroup$ Thank you for your notification. This is not a duplicate, though, because the question you referred to asked about "how to accommodate varying number of inputs in a function", however, my question is about how to change the representation of vector (based on its fixed components) in a function. $\endgroup$ – Alex Apr 9 '15 at 0:25
  • $\begingroup$ f[A_] := A.X seems to work fine. For instance, with X = {1, 3, 5, 7, 9, 11}, f[{1, 2, 3, 4, 5, 6}] yields 161.. $\endgroup$ – bbgodfrey Apr 9 '15 at 0:41
  • $\begingroup$ See also: (15749) $\endgroup$ – Mr.Wizard Apr 9 '15 at 0:48
2
$\begingroup$
f[a_List] := a.{3, 4, 5, 6, 7, 12};

f[{1, 2, 3, 4, 5, 6}]

(* 157 *)

Incidentally, do not use upper-case variables, as it is likely to conflict with internal functions (such as N).

I presume you know the number of components of a (i.e., you're not asking about inputting a vector of arbitrary length), since you apparently have a fixed x (of known length).

If you want to use x as well, try:

f[a_List] := a.(x = {3, 4, 5, 6, 7, 12})
| improve this answer | |
$\endgroup$
2
$\begingroup$
f[a__] := {a}.x

x = Range[6];
f[a1, a2, a3, a4, a5, a6]
(* a1 + 2 a2 + 3 a3 + 4 a4 + 5 a5 + 6 a6 *)

Or

g = {##}.x &;
g[a1, a2, a3, a4, a5, a6]
(* a1 + 2 a2 + 3 a3 + 4 a4 + 5 a5 + 6 a6 *)
| improve this answer | |
$\endgroup$
  • $\begingroup$ Best answer, thank you. $\endgroup$ – Cheshire Cat Apr 28 '16 at 14:11
1
$\begingroup$

If you know that x will always have 6 items then you can restrict f by

f[a_List /; a \[Element] Vectors[6, Reals]] := a.x

This will not evaluate the function when a has the wrong dimensions.

Hope this helps.

| improve this answer | |
$\endgroup$

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