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
답변 (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!