How to pass extra parameters to custom Output Function?
조회 수: 3 (최근 30일)
이전 댓글 표시
Hi,
I want to pass
test_var = 5;
to the custom output function
[state, options,optchanged] = testFCN(options,state,flag)
in the optimoptions of gamultiobj().
I tried:
[state, options,optchanged] = testFCN(options,state,flag,settings)
and
test_handle1 = @(options,state,flag) testFCN(options,state,flag,test_var);
test_handle2 = @(x) testFCN(x,test_var);
but I always get the error
Too many input arguments.
What am I doing wrong?
댓글 수: 0
채택된 답변
Voss
2022년 2월 18일
Regardless of whether you define a function handle that uses testFCN or you call testFCN directly, make sure your testFCN is defined to accept up to four input arguments.
(You can check how many arguments are given using nargin, and act accordingly.)
test_var = 5;
options = [];
state = [];
flag = false;
settings = [];
% testFCN_1 is defined as having 3 input arguments
% testFCN_2 is defined as having 4 input arguments
% testFCN is defined as having 4 input arguments, with the 4th being optional
% (see the definitions at the bottom)
% try calling testFCN_1 with 3 inputs -> OK
try
[state, options,optchanged] = testFCN_1(options,state,flag);
disp('Worked OK');
catch ME
disp(ME.message);
end
% try calling testFCN_1 with 4 inputs -> error
try
[state, options,optchanged] = testFCN_1(options,state,flag,settings);
disp('Worked OK');
catch ME
disp(ME.message);
end
% try calling testFCN_2 with 3 inputs -> different error (if 4th input is needed)
try
[state, options,optchanged] = testFCN_2(options,state,flag);
disp('Worked OK');
catch ME
disp(ME.message);
end
% try calling testFCN_2 with 4 inputs -> OK
try
[state, options,optchanged] = testFCN_2(options,state,flag,settings);
disp('Worked OK');
catch ME
disp(ME.message);
end
% testFCN (using nargin) can take 3 or 4 inputs:
% try calling testFCN with 3 inputs -> OK
try
[state, options,optchanged] = testFCN(options,state,flag);
disp('Worked OK');
catch ME
disp(ME.message);
end
% try calling testFCN with 4 inputs -> OK
try
[state, options,optchanged] = testFCN(options,state,flag,settings);
disp('Worked OK');
catch ME
disp(ME.message);
end
function [state, options,optchanged] = testFCN_1(options,state,flag) % 3 input arguments
optchanged = flag;
end
function [state, options,optchanged] = testFCN_2(options,state,flag,settings) % 4 input arguments
optchanged = settings;
end
function [state, options,optchanged] = testFCN(options,state,flag,settings) % 4 input arguments, 4th optional
if nargin < 4
% if settings is not given, use some default value
settings = [];
end
optchanged = settings;
end
추가 답변 (0개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!