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!