フィルターのクリア

Why this piece of code gives error?

1 回表示 (過去 30 日間)
Sadiq Akbar
Sadiq Akbar 2022 年 4 月 20 日
コメント済み: Steven Lord 2022 年 4 月 21 日
CostFunction='fun4sn0';
nPop=120;
nVar=4;%nVar=1000;
nPop_Initial=nPop;
nPop_Final=30;
MaxNFE=3e3;
MaxIter0=ceil(MaxNFE/((nPop_Initial+nPop_Final)/2)); % Approximate Maximum Iterations
Cr=0.5;
xmin=[0 0 0 0];
xmax=[10 10 pi pi];
%%%%%%%%%%%
NFE=0;
Gbest.Position=[];
Gbest.Cost=inf;
BestCosts=nan(1,MaxIter0);
nfe=BestCosts;
for i=1:nPop
Velocity(i,:)=zeros(1,nVar); %#ok<*SAGROW>
Position(i,:)=xmin+(xmax-xmin).*rand(1,nVar);
Cost(i)=CostFunction(Position(i,:));
PbestPosition(i,:)=Position(i,:);
PbestCost(i)=Cost(i);
PbestVel(i,:)=Velocity(i,:);
if PbestCost(i)<Gbest.Cost
Gbest.Position=PbestPosition(i,:);
Gbest.Cost=PbestCost(i);
Gbest.Velocity= PbestVel(i,:);
end
end
  2 件のコメント
Jon
Jon 2022 年 4 月 20 日
what error does it give, please cut and paste entire error message
Sadiq Akbar
Sadiq Akbar 2022 年 4 月 20 日
Thank you very much dear Jon for your response. It gives the following error:
Subscript indices must either be real positive integers or logicals.
Error in WGA1 (line 37)
Cost(i)=CostFunction(Position(i,:));

サインインしてコメントする。

採用された回答

Steven Lord
Steven Lord 2022 年 4 月 20 日
Either make your CostFunction variable a function handle to the fun4sn0 function (which is the approach I'd prefer):
CostFunction= @fun4sn0;
or use feval to evaluate the function by name.
Cost(i) = feval(CostFunction, Position(i, :));
Both of these assume that your function returns a scalar, since you're assigning its output into one element of the Cost variable.
  3 件のコメント
Image Analyst
Image Analyst 2022 年 4 月 21 日
@Steven Lord messing with function handles and feval() seems like a roundabout way to do it. Is that better than just calling the function directly like I suggested?
Cost(i) = fun4sn0(Position(i,:));
Steven Lord
Steven Lord 2022 年 4 月 21 日
@Image Analyst That is another option, and is the easiest if you want to hard-code the cost function. I think that particular name put me in "this is likely going to be used in some form of optimization" mode and in that case (the "function function" scenario, see ode45, fminsearch, fzero, integral, etc.) to keep the code as a general purpose solver you wouldn't want to hard-code the function.

サインインしてコメントする。

その他の回答 (1 件)

Image Analyst
Image Analyst 2022 年 4 月 20 日
CostFunction is a character array, not an actual function. Did you mean
Cost(i) = fun4sn0(Position(i,:));
instead of
Cost(i)=CostFunction(Position(i,:));
Thorough discussion of the error in the FAQ:
  1 件のコメント
Sadiq Akbar
Sadiq Akbar 2022 年 4 月 21 日
Also thanks a lot dear Image Analyst.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by