# optimising variables in for loop

5 views (last 30 days)
daan bosselaar on 20 Oct 2021
Answered: Alan Weiss on 22 Oct 2021
I want to optimize the variables u(k) and v(k) in the following loop to minimize the value of q_backup(k). However I have no idea what command to use, can someone help me :)? Both u and v can take any value between 0 and 1 so 0<u<1, 0<v<1
for k = 1:145
u(k) =
v(k) =
t(k) = dt*k
T_sky(k) = To(k)-8
mdot(k) = rho_a*u(k)*phi*sqrt(2*g*H*max(0, (T_a(k)-To(k))/(T_a(k))))
q_backup(k) = mdot(k)*C_a*abs(T_a(k)-T_ref)*dt+beta*(T_a(k)-T_ref).^2
T_a(k+1) = T_a(k)+(qdotp(k)+mdot(k)*C_a*(To(k)-T_a(k))+h_a*A_w1*(T_w1(k)-T_a(k))+h_a*A_w2*(T_w2(k)-T_a(k))+h_a*A_w3*(T_w3(k)-T_a(k)))*(dt/(rho_a*V_a*C_a))
T_w1(k+1) = T_w1(k)+(v(k)*Ik(k)*alpha_w1+labda*(T_sky(k).^4-T_w1(k).^4)+h_o*(To(k)-T_w1(k))+h_a*(T_w1(k)-T_a(k)))*(A_w1*dt)/(rho_w1*V_w1*C_w1)
T_w2(k+1) = T_w2(k)+(Ik(k)*alpha_w2+labda*(T_sky(k).^4-T_w2(k).^4)+h_o*(To(k)-T_w2(k))+h_a*(T_w2(k)-T_a(k)))*(A_w2*dt)/(rho_w2*V_w2*C_w2)
T_w3(k+1) = T_w3(k)+(0.5*v(k)*Ik(k)*tau_w1*alpha_w3+h_a*(T_w3(k)-T_a(k)))*(A_w3*dt)/(rho_w3*V_w3*C_w3)
end

Alan Weiss on 22 Oct 2021
It is not clear to me whether you want to minimize q_backup(k) for one particular value of k or for all k from 1 to 145.
Generally, you would have to pick one particular value of k, because optimization can minimize only a single scalar function. For example, if you can only lower q_backup(2) by raising the value of q_backup(1), then these are called "competing" objectives, and you cannot lower both at the same time.
So you need to decide what it is you are trying to do. Maybe you want to minimize the sum of squares of the vector q_backup:
fun = sum(q_backup^2); % Find the smallest mean square value
That is a scalar function and you can minimize it. You might want to try the Problem-Based Optimization Workflow. You will have to use the fcn2optimexpr function to wrap max and abs, as these are not supported operators for optimization variables.
Good luck,
Alan Weiss
MATLAB mathematical toolbox documentation