Sum Of Series variables from Vector.
1 次查看(过去 30 天)
显示 更早的评论
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 2x2 and R 1x1.
[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.
2 个评论
采纳的回答
Stephen23
2020-6-7
编辑:Stephen23
2020-6-8
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);
4 个评论
Stephen23
2020-6-8
编辑:Stephen23
2020-6-8
Your code is missing cumsum at the end. This is required because your formula for F(n) is just F(n-1) plus a new term. So we might as well just calculate all the terms once (there is no point in repeating them) and then get the cumulative sum of them. That is what my code does.
If you don't want to use cumsum then just add the terms in the loop, e.g.:
tmp = 0;
for k = 1:n
tmp = tmp + X(:,k).'*Q*X(:,k) + U(:,k).'*R*U(:,k);
F(k) = tmp;
end
If you want that code as a function, then just define it inside an Mfile:
For example:
function out = myfun(z)
... my code
out = sum(F); % you need this at the end!
end
and provide a handle of that function to fmincon, just as the documentation shows:
x = fmincon(@myfun,...)
Note that because fmincon requires the function output to be a scalar you will have to return a scalar from the function, e.g. the sum of F as I showed above.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Performance and Memory 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!