# 'The objective function is not a scalar' in NMinimize

I am trying to do a GMM(Generalized Method of Moments) by NMinimize, it comes up with the warning 'The objective function is not a scalar', here's what I have tried:

1. I adjusted the function step by step and found that the problem is about the minus e=y-yPred, after I delete the minus, it worked.But I really can't understand why.
2. When I use the functions directly, it gives a scalar. I think this is the evidence that my dimension of vector and matrix is right, which I have checked also.

I am new with the matrix calculate, I think this problem must be somehow stupid, but I can't fix it.Sorry :(

ClearAll[datax, datay, Winv, params, gmmObjective, beta]

(*Setting*)
datax = {{1, 2, 3}, {4, 5, 6}};

datay = {1, 2};

Winv = IdentityMatrix[3];

(*Original function*)
gmmObjective[params_, y_, x_, Matr_] :=
Module[{yPred, e, moments, avgMoment, juvalue},
yPred = x . params;
e = y - yPred;
moments = e . x;
juvalue = moments . Matr . Transpose[moments];
Return[juvalue];
]

NMinimize[{gmmObjective[beta, datay, datax, Winv],
Element[beta, Vectors[3, Reals]]}, beta]

gmmObjective[params_, y_, x_, Matr_] :=
Module[{yPred, e, moments, avgMoment, juvalue},
yPred = x . params;
e = yPred;
moments = e . x;
juvalue = moments . Matr . Transpose[moments];
Return[juvalue];
]

NMinimize[{gmmObjective[beta, datay, datax, Winv],
Element[beta, Vectors[3, Reals]]}, beta]

• The porblem is with beta... try NMinimize[ gmmObjective[{beta1, beta2, beta3}, datay, datax, Winv], {beta1, beta2, beta3}] with your original objective and it gives an answer. Commented Nov 25, 2023 at 3:21

You define beta in NMinimize as a scalar. Replacing beta by: 1 and evaluating:

gmmObjective[1, datay, datax, Winv]

{{1, 2, 3}, {4, 5, 6}} . 1 . {{1, 2, 3}, {4, 5, 6}} .
Transpose[{{1, 2, 3}, {4, 5, 6}} . 1 . {{1, 2, 3}, {4, 5, 6}}]


You see: "...6}}.1.{{1,2..." You can not use the Dot product for a scalar. Your statement:

yPred = x . params


is wrong.