I try to create a simple optimisation script. Here is my code:
# Analysis gives the initial inputs and outputs
$initialinputs
$initialoutputs
# The objective function
$F = ([math]::pow($initialinputs, 2)) * 2 - 3* $initialinputs
# Differentiation of the objective function
$DF = 2 * $initialinputs - 3
$ScaleFactor = 0.2
# If the optimum solution has been obtained, two termination measurements:
# maximum iteration and termination criterion(gradient)
$Maxloop = 100
$Termi = 0.001
# Create arrays
$InputsArr = @() #The array of inputs
$FunctionArr = @() #The array of function values
$DFunctionArr = @() # The array of differentiation values (Gradient)
# Calculations
#$InputsArr[0] = $initialinputs #The first input
#$FunctionArr[0] = $F[$InputsArr[0]]
#$DFunctionArr[0] = $DF[$inputsArr[0]]
for ($Innerloop = 1; $Innerloop -le $Maxloop; $Innerloop++)
{
# Calculate the second input
$InputsArr[$innerloop] = $InputsArr[$Innerloop - 1] - $ScaleFactor * (2 * $InputsArr[$Innerloop - 1] - 3)
$initialinputs = $InputsArr[$Innerloop]
# Calculate the function value
$FunctionArr[$innerloop] = ([math]::pow($initialinputs, 2)) * 2 - 3 * $initialinputs
Return, $FunctionArr
# Calculate the gradient value
$DFunctionArr[$innerloop] = 2 * $initialinputs - 3
return, $DFunctionArr
# If the gradient value less than the termination criterion (gradient),
# break the loop
if ($DFunctionArr[$innerloop] -le $Termi)
{
break
}
}
I created the empty arrays and then use the for loop to do the optimisation and store the outputs in the arrays. But I got some errors as shown below:
ERROR: + $InputsArr[$Innerloop] = $initialinputs ERROR: + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ERROR: + CategoryInfo : OperationStopped: (:) [], IndexOutOfRangeException ERROR: + FullyQualifiedErrorId : System.IndexOutOfRangeException ERROR: + $FunctionArr[$innerloop] = $Functionoutput ERROR: + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ERROR: + CategoryInfo : OperationStopped: (:) [], IndexOutOfRangeException ERROR: + FullyQualifiedErrorId : System.IndexOutOfRangeException
I am not quite sure how to fix the errors. How to return the value to the arrays? Is += the only way to do so? I get confused about the arrays now.