How to code up an objective function that has summations in it and then use it with fminunc?

1 view (last 30 days)
I am trying to code up a Model Predictive Controller (MPC) using the fminunc function to give me values of u that would minimize
J = Sum[{N1:N1+10} (reference_state-predicted_state(N1:N1+10))^2] + Sum[{N1:N1+3} u(N1:N1+3)^2]
where N1 is current time, or for simplicity J= Sum(term1)^2 + Sum(term2)^2. So, basically, I need to find the vector of u's in term 2 based on the vector of predicted errors in term 1 that would minimize J. To begin with, I have considered a prediction horizon of 10 and a control horizon of 3.
My objective function looks like this
global setpoint
global x_opt
[n,m] = size(x_opt);
term1 = 0; term2 = 0;
for i = 1:n
sum1 = (x_opt(i,1)-setpoint)^2;
term1 = term1 + sum1;
sum2 = u(i)^2;
term2 = term2 + sum2
end
J = term1 + term2
here x_opt contains the predicted_state values for the length of the prediction horizon and setpoint is my reference_state which is a constant for all time. I am calling fminunc in the main function after computing all the predicted_state values for the length of the prediction horizon.
So, when I run this code, I get the following error
Attempted to access x(2); index out of bounds because numel(x)=1.
which leads me to believe that there is something wrong with my objective function. I have never used fminunc or fmincon with summations in the objective function and this is my first time coding up a MPC, therefore, any help/suggestions would be highly appreciated.

Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!