Define a callback function in a script passing parameters

5 ビュー (過去 30 日間)
Stefano Massardi
Stefano Massardi 2020 年 11 月 6 日
編集済み: Piyush Aggarwal 2020 年 11 月 9 日
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

回答 (1 件)

Piyush Aggarwal
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.
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

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by