Cutting time using optimization instead of a potentially endless for loop ?
2 次查看(过去 30 天)
显示 更早的评论
Okay, so I have written a code that generates two linear piecewise functions: a hot stream and a cold stream. The hot stream begins below the cold stream and the x axis (temperatures) is fixed. Essentially I am trying to move the hot stream up (positive y direction) until the minimum temperature difference reaches some variable. As of now, I have a for loop that works great, but takes roughly four minutes to run;according to viewer this is all due to the for loop and using ppval inside the for loop. The code I have now for this part is:
dhdc = [];
raise_hot_y = 0;
for i = 1:length(unique_cold_temps)
dhdc(i) = (interpFunction((Hcoldpt(i)+raise_hot_y),hotStreamInterp))- unique_cold_temps(i);
end
dcdh = [];
for i=1:length(unique_hot_temps)
dcdh(i) = interpFunction((Hhotpt(i)+raise_hot_y), coldStreamInterp) - unique_hot_temps(i);
end
while min(min(abs(dhdc)), min(abs(dcdh))) >= epsilon
for i = 1:length(unique_cold_temps)
dhdc(i) = (interpFunction((Hcoldpt(i)+raise_hot_y),hotStreamInterp))- unique_cold_temps(i);
end
for i=1:length(unique_hot_temps)
dcdh(i) = interpFunction((Hhotpt(i)+raise_hot_y), coldStreamInterp) - unique_hot_temps(i);
end
raise_hot_y = raise_hot_y + .1;
end
Is there some way I can use an optimization technique or solver to solve for the raise_hot_y value (how much I must increase the intercept of the function) that is much more time efficient?
0 个评论
回答(1 个)
Andrew Newell
2012-1-7
Certainly there is, but I'm not sure quite how to formulate it with the information given. It will look something like this. Put your hot and cold points into a single variable, e.g., hotcoldpt, and do the same for your interpolation hotcoldStreamInterp and your target values unique_temps. Vectorize interpFunction and then create an anonymous function:
f = @(x) interpFunction(Hholdcoltpt+x,holdcoldStreamInterp)-unique_temps;
Finally, solve:
raise_hot_sol = fsolve(f,raise_hot_sol_guess);
This finds the solution to f=0.
2 个评论
Andrew Newell
2012-1-8
I'm assuming they are independent. The function |interpfunction| is just a black box that takes some vector |x| and outputs a vector |y|. It could call a different function for each component of the input - if you wished.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Startup and Shutdown 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!