Not enough input arguments in Schaffer
1 次查看(过去 30 天)
显示 更早的评论
Though I'm new to Matlab, I can't believe I could get this wrong. Matlab told me" Error using Schaffer (line 2) Not enough input arguments." But I can't find the problem and fix it. The following is my code--really simple, Please help me, thanks a lot!
function f=Schaffer(x)
f=0.5+((sin((x(1)^2+x(2)^2)^(1/2)))^2-0.5)/(1+0.001*(x(1)^2+x(2)^2))^2;
x0=[-10,10];
[x,fval]=fminsearch(Schaffer,x0);
end
回答(1 个)
Abhishek
2025-3-3
Hi,
It looks like you're running into a common issue when working with function handles in MATLAB. The error you're encountering stems from attempting to define the function and call it within the same file. I tried this in MATLAB R2024b, and I faced the same issue.
In MATLAB, functions can either be saved in function files or script files, but script files cannot share the same name as a function within the file.
Additionally, functions must be declared at the start, and the name of the file must match the name of the first function if saved in a function file. Please refer to the below documentation which explains that functions can either be defined in a function file that only contains the function definition, or in a script file that contains function definitions and commands. https://www.mathworks.com/help/releases/R2024b/matlab/ref/function.html
In order to resolve this issue, you can define the function in a separate file and call it from another file. You may try following the below steps to achieve this in MATLB R2024b:
- Define the function in a file named “Schaffer.m”:
function f = Schaffer(x)
f = 0.5 + ((sin((x(1)^2 + x(2)^2)^(1/2)))^2 - 0.5) / (1 + 0.001 * (x(1)^2 + x(2)^2))^2;
end
2. Call the function from another file. I have created a file named “Test.m” in the same directory as “Schaffer.m” and called it from there:
x0 = [10, -10];
[x, fval] = fminsearch(@Schaffer, x0);
disp('Optimised values of x:');
disp(x);
disp('Function value at the optimum (fval):');
disp(fval);
3.Run the “Test.m” file. The output is as follows:
>> Test
Optimised values of x:
12.0419 -10.0666
Function value at the optimum (fval):
0.1782
Hope this solves the issue .
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Random Number Generation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!