Info
此问题已关闭。 请重新打开它进行编辑或回答。
help with emplementing a function
1 次查看(过去 30 天)
显示 更早的评论
Hello,
Can someone help me with implementing the attached function please.
I am trying to minimise the function using genetic algorithm (GA). To do so, I need to find the optimal v(t) that returns the minimum cost.
For now, I need to implement the function for the On mode ONLY. I am struggeling with implementing the function.
-1 <= V(t) <= 5
here is my attempt:
clear variables;
close all;
clc;
vt = -1:0.01:5;
cost = @(vt) costfunction(vt);
Here is how I defined the cost function:
function cost = costfunction(vt)
PiD = 30 ;
PiC = 10 ;
PiP = 50;
A = 4/3;
h = 4;
pvt_1= @(vt) vt-4;
pvt_2= @(vt) abs(-vt);
if (vt >= 0 & vt <= 4)
cost = ((PiC*(vt./A))+PiD)/(vt./A);
elseif (vt > 4 & vt <= 5)
cost = ((PiP*abs(integral(pvt_1,0,inf)))+PiC*((vt)./A)+PiD)/(vt./A);
else
cost = ((PiP*integral(pvt_2,0,inf))+PiC*((abs(vt)+h)./A)+PiD)/((abs(vt)+h)./A);
end
end
A drawing explains the problem is attached.
5 个评论
回答(1 个)
Walter Roberson
2020-5-2
vt = -1:0.01:5;
That defines vt as a vector.
cost = @(vt) costfunction(vt);
That defines cost as a function handle that takes exactly one parameter by position, and passes that parameter to costfunction. This does not use the vector vt that you defined, and is the same as
cost = @costfunction
or as
cost = @(ShesPiningForTheFjordsSheIs) costfunction(ShesPiningForTheFjordsSheIs);
Your code does not show any invocation of cost() so we do not know what you are passing to it.
However... we can get the hint that probably you are passing a vector of values to cost(), which would pass them to costfunction()
if (vt >= 0 & vt <= 4)
In MATLAB, an if statement or while statement is considered to be true if all of the values it is asked to process are non-zero. If there is even one zero being tested, the test is considered to fail. Now consider what happens if you pass in -1:0.01:5 as vt:
if all([-1:0.01:5] >= 0 & [-1:0.01:5] <= 4)
and we can look and see that -1 >= 0 is false, and although -1 <= 4 is true, the & causes the pair together to be true. So we have identified at least one element being tested that will come out false (which is 0), so we can see that the if fails, no matter what the status of any of the other elements in -1:0.01:5 .
You have three choices:
- Call costfunction on only one value at a time, such as by using a for loop or using arrayfun(); or
- Have your code internally loop over input vectors, saving the user from having to do the looping; or
- Vectorize your code by using logical indexing. Even if you do not choose to use logical indexing this time, you really should read about logical indexing, as it gets used a lot (and would work well for you.) https://blogs.mathworks.com/loren/2013/02/20/logical-indexing-multiple-conditions/
0 个评论
此问题已关闭。
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!