MATLAB: Sum Of Series variables from Vector.

cost functionmatrixsum of series

Hello everyone,
I know this text seems to be long, but it is not. Just for clarification. Skip to [3] to see the Problem. Please help me :)!
[1] Description of the Problem:
Assume that there is a Vector called z=[ ]; this is a flexible Vector that means if i need for my
"x0" "u0"
system for example: z[1]. z is gonna be z=[ 1; 1; 3]; (1)
"x0" "u0" "x1" "u1"
if i need for my system z=[2]. z is gonna be z=[ 1; 1; 3; 0; 2; 0 ]; (2)
"x0" "u0" "x1" "u1" "x2" u2"
z[3] z=[ 1; 1; 3; 0; 0; 5 ; 7; 2; 0;]; (3)
and so on…
I need to make a function of
if z[3] = f(x0,u0,x1,u1,x2,u2) (3')
if z[2] = f(x0,u0,x1,u1) (2')
and so on…
to bring light into the dark our vector x0 would be z(1:2);
u0 would be z(3);
x1 would be z(4:5);
u1 would be z(6);
and so on…
Furthermore there are also 2 more matrices (Q and R, they are given), but they will not change over time. Q has the Dimensions of 2×2 and R 1×1.
[2] Goal:
The goal is to take the and the from the z vector and to build a automatic generated function in the following form.
for the example of z[2]:
f(x0,u0,x1,u1) = +
or z[3]:
f(x0,u0,x1,u1,x2,u2) = + +
[3] My idea:
i wanted to do it with the sum of series where the summation index will be i (to build the individual and ).
for z=[2] (see. [2]),;
f(x0,u0,x1,u2) = (4)
Now, i just have to fill the individual and to get the Solution. Just like:
x0 u0 x1 u1
f( z(1:2) , z(3), z(4:5), z(6)).
i really dont know how to build the function (4) in Matlab with n (depends on system) variables.
Sincerely yours,
M.S.

Best Answer

Why not just use a loop?:
Q = [1,2;3,4];
R = 5;
z = [1;1;3;0;0;5;7;2;0];
%
X = [z(1:3:end),z(2:3:end)].';
U = z(3:3:end).';
n = numel(U);
F = nan(1,n);
for k = 1:n
F(k) = X(:,k).'*Q*X(:,k) + U(:,k).'*R*U(:,k);
end
F = cumcum(F);