2

For example I have a function for simplicity

F[x_]:= x[[1]]^2 + x[[2]]^2 + ...(some function of x as a vector)

How to minimize this function using NMinimize (without using separate variables {x,y,z...}, but using x itself as a vector)

wilddev
  • 121
  • 1

2 Answers2

4

You can use a syntax like this to specify that your variable is a vector:

NMinimize[Norm[x], x ∈ FullRegion[3]]

{1.05304*10^-8, {x -> {-7.46531*10^-9, -7.10577*10^-9, -2.16042*10^-9}}}

Use Indexed to access specific components of the vector. E.g.,

NMinimize[Indexed[x,1]^2 + Indexed[x,2]^4, x ∈ FullRegion[2]]

When doing this with more complicated functions, it may be necessary to define them in a way so that they won't evaluate for non-vector arguments. Use _?VectorQ in the argument pattern. Test your function with a single symbolic argument to make sure it doesn't evaluate to anything undesirable.

Example:

This is incorrect:

Clear[f]
f[vec_] := vec[[1]]^2 + vec[[2]]^2

enter image description here

Even though it "works", trying to take the part of a symbol is an error. More complex cases that allow such sloppiness will fail completely at best, and give you wrong results at worst.

This is correct:

Clear[f]
f[vec_?VectorQ] := vec[[1]]^2 + vec[[2]]^2
Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263
0

The following is a very simple implementation of what you have requested

F[x_] := x[[1]]^2 + x[[2]]^2 + Cosh[x[[4]] - 2]
X = Table[x[i], {i, 1, 4}];
NMinimize[F[X], X]
(* {1., {x[1] -> -5.00268*10^-9, x[2] -> -6.20339*10^-9, 
  x[3] -> 1.04214, x[4] -> 2.}} *)

It might be simpler to write your function directly in terms of x[1], x[2],..., but that is up to you.

mikado
  • 16,741
  • 2
  • 20
  • 54