1
$\begingroup$

Here is my problem: I've got an objective function f[..] to minimize (numerically with the help of FindMinimum[...] procedure) that depends on a variable number of arguments, i.e. one time it will be minimized when depending on 5 variables, next time on 10, and another on 20 or even more. Instead of creating separate function definitions for each of these cases, I would like to define my objective function once like f[X_], where inside the body of the function I could refer to the optimizable arguments in this way: X[1],X[2],X[3],...,X[n]. The body of the function involves numerical solution to a differential equation with the help of NDSolveValue[..] procedure, so I also want to define my objective function that is only intended to evaluate for numerical values of the variables like this: f[X_?NumberQ] := Cos[X[1]^2 - 3 X[2]] + Sin[X[2]^2 + X[1]^2]. Unfortunately, this approach does not work and I cannot manage to get it right. Please, provide some help. Looking forward to your feedback and suggestions. Thank you in advance!

$\endgroup$
2
  • $\begingroup$ f[X_?(VectorQ[#, NumericQ] &)] := Cos[X[[1]]^2 - 3 X[[2]]] + Sin[X[[2]]^2 + X[[1]]^2]; f[{1., 2.}] $\endgroup$
    – Bob Hanlon
    Apr 10, 2023 at 16:26
  • $\begingroup$ Thank you very much, Bob. Your definition works just fine, but I still have an issue with minimizing this function. Here's what I tried and got as a response from the system: FindMinimum[f[x], {x[[1]], 5.0}, {x[[2]], 6.0}] -> FindMinimum::vloc: The variable x[[1]] cannot be localized so that it can be assigned to numerical values. Any thought on how to overcome this issue? $\endgroup$ Apr 10, 2023 at 18:04

1 Answer 1

2
$\begingroup$
$Version

(* "13.2.1 for Mac OS X x86 (64-bit) (January 27, 2023)" *)

Clear["Global`*"]

f[x_?(VectorQ[#, NumericQ] &)] := 
  Cos[x[[1]]^2 - 3 x[[2]]] + Sin[x[[2]]^2 + x[[1]]^2];

NMinimize[{f[x], x ∈ Vectors[2, Reals]}, x]

(* {-2., {x -> {-5.32352, -6.26134}}} *)

NMinimize[{f[x], x ∈ Rectangle[{-3, -3}, {3, 3}]}, x]

(* {-2., {x -> {-1.37638, 1.67868}}} *)

NMinimize[{f[x], x ∈ Vectors[2, PositiveReals]}, x]

(* {-2., {x -> {2.12265, 0.454686}}} *)

NMinimize[{f[x], x ∈ Rectangle[{0, 0}, {3, 3}]}, x]

(* {-2., {x -> {1.37638, 1.67868}}} *)
$\endgroup$
1
  • $\begingroup$ Thanks, Bob. Works like a charm. $\endgroup$ Apr 11, 2023 at 17:46

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.