Can I pass arguments to a @callbackFcn?

17 次查看(过去 30 天)
Hello,
I am reading some data from a serialport by using this function:
configureCallback(s,"terminator",@readSerialData)
The function looking like this
function readSerialData(s,~)
...
end
But how can I do to use arguments in the @readSerialData, for example I want to use this two arguments
function readSerialData(s,~,operation,mode)
...
end
How can I "pass" these two variables from the "configureCallback" line to the function?
Thank you!!

采纳的回答

J. Alex Lee
J. Alex Lee 2021-7-29
configureCallback(s,"terminator",@(src,evnt)readSerialData(src,evnt,operation mode))
So the first parentheses specify the interface to the function handle you want to create, and the second parentheses is the interface to the actual function you want to make a handle of. The variables in the first parantheses must appear as-is in the list of the second parantheses; they are the special inputs. The rest of the variables in the list of the 2nd parantheses will just be "static".
A simpler example might be
mySpecificFn = @(x)myGeneralFn(x,1,2,3)
function y = myGeneralFn(x,a,b,c)
y = a*x.^2 + b*x + c;
end
which you can kind of glean from some examples in the documentation, but maybe it's not so clear that that is the same as
a = 1
b = 2
c = 3
mySpecificFn = @(x)myGeneralFn(x,a,b,c)
function y = myGeneralFn(x,a,b,c)
y = a*x.^2 + b*x + c;
end

更多回答(1 个)

Bruno Luong
Bruno Luong 2021-7-29
% Assuming operation,mode are defined
% operation = ...
% mode = ...
configureCallback(s,"terminator",@(s,t) readSerialData(s, t, operation, mode));

Community Treasure Hunt

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

Start Hunting!

Translated by