How can I pass a variable (numeric) through a callback event when I pressed a key in my figure?
조회 수: 8 (최근 30일)
이전 댓글 표시
Hello,
I have an issue;
I am collecting data in a while loop and I want to store this data in my callback event when I press a key in my figure.
This does not work at all.
Could you please help me in this topic?
My code example:
set(gcf, 'KeyPressFcn', {@GetData, calibration});
while true
pause(0.00001);
[calibration] = ml_CANapeReadCalibrationObject(moduleHandle(1,2), 'F_DE_f_1', 1);
sensorData = [sensorData; calibration(1)];
plot(sensorData);
drawnow;
disp('getting data');
end
function GetData(src, event, sensorData)
finalData = [finalData; sensorData];
pause(1);
end
댓글 수: 2
Jan
2021년 10월 20일
This piece of code is not running. It is not clear if the callback is a nested function or not. "Does not run at all" is not useful to explain the problem. Do you get an error message?
답변 (2개)
Walter Roberson
2025년 4월 30일
set(gcf, 'KeyPressFcn', {@GetData, calibration});
That code does not bind "calibration" to whatever the then-current value of the variable "calibration" is. Instead, it reads the value of the variable "calibration" as of the time that the set() is performed, and sets the KeyPressFcn to use that recorded version of "calibration".
There is no syntax for setting the KeyPressFcn for retrieving the then-current value of a variable. You would have do something such as continually assigning the variable in the 'base' workspace, and telling the KeyPressFcn to evalin('base')
finalData = [finalData; sensorData];
finalData is not defined inside of that function. You would have to something such as making it a shared variable and making GetData a nested function.
댓글 수: 0
Vedant Shah
2025년 4월 30일
To store the data present in “sensorData”, it is essential to ensure that the callback function receives the correct value of the “sensorData” variable. The following approach can be utilized which makes use of “setappdata” and “getappdata”:
Firstly, modify the setting line to ensure that no data is passed in the callback function:
set(gcf, 'KeyPressFcn', @GetData);
The “setappdata” function can be used to store the variable “sensorData” . It can be added just before plotting it:
setappdata(gcf, 'sensorData', sensorData);
Additionally, the “GetData” function can be modified to make use of “getappdata” and to ensure that the “finalData” variable remain conistent:
function GetData(src, event)
sensorData = getappdata(src, 'sensorData');
persistent finalData
if isempty(finalData)
finalData = [];
end
finalData = [finalData; sensorData];
pause(1);
end
The use of the “persistent” keyword ensures consistency when saving values multiple times during code execution.
For further information, refer to the following MATLAB documentation links:
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!