1
$\begingroup$

Is there an equivalent to the MATLAB parameter nargin that can be used in AceGen?

For example, consider a function that takes in two vectors and an optional scalar. If only two vectors are inputted then the output is the dot product of the vectors. If three parameters are inputted then the output is the dot product of the vectors multiplied by the inputted scalar.

The example below illustrates the question.

(* LAUNCH ACEGEN *)
<< AceGen`;

(* INITIALIZE ACEGEN SESSION *)
SMSInitialize["ExampleFunction", "Language" -> "Matlab", 
  "Mode" -> "Optimal"]; 
SMSModule["ExampleFunction",
  Real[Vec1$$[2], Vec2$$[2], Scalar$$, Output$$[2]],
  "Input" -> {Vec1$$, Vec2$$, Scalar$$},
  "Output" -> {Output$$}
  ];

(* EXTRACT INPUT DATA *)
{Vec1, Vec2, Scalar} \[DoubleRightTee] {SMSReal[{Vec1$$}], 
   SMSReal[{Vec2$$}], SMSReal[{Scalar$$}]};
Vec1 \[DoubleRightTee] SMSReal[Table[Vec1$$[i], {i, 1, 2}]];
Vec2 \[DoubleRightTee] SMSReal[Table[Vec2$$[i], {i, 1, 2}]];
Scalar \[DoubleRightTee] FromDigits[Scalar]; 

(* PERFORM CALCULATION *)
NumberOfInputArguments = 2; (* How do I determine this? *)
If[NumberOfInputArguments == 2,
  Output \[DoubleRightTee] (Vec1 . Vec2);,
  Output \[DoubleRightTee] Scalar (Vec1 . Vec2);];

(* EXPORT DATA *)
SMSExport[Output, Output$$];
SMSWrite[];
$\endgroup$

1 Answer 1

1
$\begingroup$

In the case you mentioned as an example, you could take advantage of the fact that $1$ is an invariant for multiplication and use it as the default value for the scalar:

ClearAll[custom]
custom[v1_?VectorQ, v2_?VectorQ, scalar_: 1] := scalar Dot[v1, v2]

custom[{a, b}, {c, d}]   (* Out: a c + b d     *)
custom[{a, b}, {c, d}]   (* Out: (a c + b d) s *)

More generally, use two definitions. The right definition will be selected depending on the number of arguments:

ClearAll[custom2]
custom2[a_, b_] := "two arguments"
custom2[a_, b_, c_] := "three arguments"

custom2[{x, y}, {b, d}]     (* Out: "two arguments"   *)
custom2[{x, y}, {b, d}, 4]  (* Out: "three arguments" *)
$\endgroup$

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.