Define a callback function in a script passing parameters
5 次查看(过去 30 天)
显示 更早的评论
the question can be more general:
how to hanle a callback function call with @function in a matlab script, also passing parameters. I'm also talking aboutthe syntax (usually i used them in a GUI)
In my specific case:
i'm using a CAN and I want to transmit-receive messages at the same time. I'm trying to use an asyncronus transmission and assign a callback function to handle data when i receive messages. I don't know how handle @receivingFcn since i don't know if i shall define it as a normal function and how to pass parameters
The script is:
% I create a CAN channel
txCh = canChannel('NI','CAN1');
% Create the messages to send using the canMessage function.
msgTx = canMessage(72, false, 6);
% I assign a callback function when i receive a message
txCh.MessageReceivedFcn = @receivingFcn;
txCh.MessageReceivedFcnCount = 30;
% Register each message on the channel at a specified periodic rate.
transmitPeriodic(txCh, msgTx, 'On', 0.01);
the receivingFcn should use the channel and a table, and just contain:
rxMsg = receive(txCh, Inf, 'OutputFormat', 'timetable');
% I save the msg in a txt
rxMsgTable = timetable2table(rxMsg);
tableRx.table2=[tableRx.table2; rxMsgTable];
writetable(rxMsgTable, ['test' char(rxMsg.Time(1)) '.txt'])
Thanks
0 个评论
回答(1 个)
Piyush Aggarwal
2020-11-9
编辑:Piyush Aggarwal
2020-11-9
Hello Stefano,
I hope the following simple code snipet will clear your doubt on the use of function handles and parameter passing in them.
% Say you have the following simple function to calculate Geometric mean of two vectors x & y
function out = myFunc(x, y)
out = sqrt(x .* y);
end
Now you want to create a handle to this function and call it with some parameters inside some .M script
% Inputs or the parameters with which you want to call the function
in1 = [25 18];
in2 = [1 2];
% Create handle to function
fHndl = @myFunc
% Call your function with the inputs
myOut = fHndl(in1, in2);
The Function handle notation is particularly useful when you need to pass functions as an input to another function.
You may refer to the documentaion for more details : https://www.mathworks.com/help/matlab/matlab_prog/creating-a-function-handle.html
If you were looking for "How to pass multiple extra parameters to a function using the @ operator ", refer to this documentation link : https://www.mathworks.com/help/optim/ug/passing-extra-parameters.html
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 National Instruments Frame Grabbers 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!