# using array elements in minimization

I have switched from mupad to Mathematica, however the syntax is completely different here. I want to

Minimize [{Sum[(y[[i]]-3)^2,{i,1,c}], Sum[y[[i]],{i,1,c}]==10},y[[i]]]


for parameter c. Mathematica shows me

Part::pspec: Part specification i is neither a machine-sized integer nor a list of machine-sized integers.

First, you can define a vector of all the y's

z = Array[y, 3]

where I'll use 3 for concreteness. Now you can minimize your function the over the vector z using

 Minimize[{(z - 3).(z - 3), Total[z] == 10}, z]


{1/3, {y -> 10/3, y -> 10/3, y -> 10/3}}


So the minimum value is 1/3 and this is achieved at the point where y=y=y=10/3. Somewhat more generally, you can replace the "3" in the minimize command with any vector:

v= {2.06, 5.83, 7.86};
Minimize[{(z - v).(z - v), Total[z] == 10}, z]


{11.0208, {y -> 0.143333, y -> 3.91333, y -> 5.94333}}


Or perhaps different constraint functions such as known mean and variance:

Minimize[{(z - v).(z - v), Mean[z] == 5.3636, Variance[z] == 5.2545}, z]


which also gives a nice simple answer.

• If c i.e., number of elements in z can be defined as a parameter? – remo May 25 '13 at 11:51
• I thought you wanted a numerical solution? That means c needs to take on some concrete value. The above method works for any c, but it needs to be something. – bill s May 25 '13 at 11:58
• Thank you for your help. My code is (in mathematica): yppA = Array[ypp, 3] Minimize[{c2 \!$$\*UnderoverscriptBox[\(\[Sum]$$, $$i = 1$$, $$3$$] \*SuperscriptBox[$$(yppA[[i]] - {2.06, 5.83, 7.86}[[ i]])), (2)]) + c1 \!( *UnderoverscriptBox[([Sum]), (i = 1), (3)] *SuperscriptBox[((yppA[[i]] - {2.2, 5.45, 7.47}[[ i]])$$, $$2$$]\), Mean[yppA] == 5.3636 && Variance[yppA] == 5.2545}, yppA]. But it shows some errors: NMinimize::nnum: "The function value 216.338\ c1+228.797\ c2 is not a number at {ypp,ypp,ypp} = {14.4555,0.918621,0.716689}" – remo May 25 '13 at 12:00
• Sorry for bad formatting – remo May 25 '13 at 12:05
• @remo you can update your question to show additional code. – Thies Heidecke May 25 '13 at 14:16