# Optimization of multiple variables without any toolbox

2 views (last 30 days)
Anil Kumar on 27 Jul 2021
Commented: Anil Kumar on 30 Jul 2021
I have 5 variables, say l1,l2,g1,g2,g3. I want to optimize the gi (i=1,2,3) inside the two loops of l1 and l2 i.e. for each combination of l1 and l2, I want an optimal set of g_i for which the computed value should show a maximum and so on for the next values of l1 and l2. I don't have any tool box for this and I want to optimize without those.
fid = fopen( sprintf(.......))
for l1=0:0.01:1
for l2:0:0.01:1
% optimization of gi
for g1=0:0.01:0.5
x2=[];
for g2=0:0.01:0.5
for g3=0:0.01:0.5
maxen=.....%some calculations
x2=[x2;g2 g3 maxen];
end
[p, q]=max(x2(:,3));% max with indices
end
x3=x2(q,1);%g2
x4=x2(q,2);%g3
x5=x2(q,3);%maxen
end
fprintf(fid,'%f %f %f %f %f\t %f %f \r\n',l1,l2,g1,x3,x4,x5,maxen);
end
end
fclose(fid);
I tried for a simple case for fixed l2 and fixed g1 but the result of maxen and x5 doesnt match while writing x2=[] outside g2 to get proper indices of g2 and g3 for that maximum value of maxen (writing in the .dat file). However, if write x2=[] inside g2, I lost the precise value of g2 as it shows end values only but with optimal g3 and equal maxen and x5 there. How can I optimize gi and find this optimal set there for maximum of maxen for each value of two outer loops (l1,l2)?.
if optimization is not possible with this way, do I need to use any algorithms for this?
Please suggest other alternates for the same.

Jeff Miller on 28 Jul 2021
If I understand the question, your basic approach seems OK but your code isn't structured quite right. I think this is closer to what you are after (but haven't checked it).
for l1=0:0.01:1
for l2=0:0.01:1
% optimization of gi
x2=[];
for g1=0:0.01:0.5
for g2=0:0.01:0.5
for g3=0:0.01:0.5
maxen = g1^2-g2^3+g3^4 + l1 - l2; % example calculation
x2=[x2; g1 g2 g3 maxen];
end
end % end g2 loop
end % end g1 loop
% Now check the results for this l1/l2 combination
[p, q]=max(x2(:,4));% max with indices
g1 = x2(q,1); % g1
g2 = x2(q,2);%g2
g3 = x2(q,3);%g3
maxen =x2(q,4);%maxen
fprintf('%f %f %f %f %f\t %f %f \r\n',l1,l2,g1,g2, g3,maxen);
end
end
Anil Kumar on 30 Jul 2021
Dear Jeff, I agree with you. Thanks.