Using addlistener function - how to output values from event handler?
Mostrar comentarios más antiguos
I would like to write a script that looks for changes to a text file and saves the values recorded in the text file to the workspace.
I am following the example ('Monitor Changes to a .TXT File') on this page: https://uk.mathworks.com/help/matlab/matlab_external/use-net-events-in-matlab.html.
I am able to monitor my text file and print the change in text, however I am stuck on how I can pass the values to the workspace.
If I use the code given in the example, my code looks like the following scripts and I have highlighted what I am would like to do in the comment lines. In this example, I would like to know how I must modify the code, so that the values, x, y and z, found in the 'eventhandlerChanged' function are output in such a way that they will be accessable from the main script.
I appreciate any help you can offer with this.
% Main script that looks for changes in the text file, 'text_file.txt' and
% calls the function 'eventhandlerChanged' upon registering a change
file = System.IO.FileSystemWatcher('c:\work\temp');
file.Filter = 'text_file.txt';
file.EnableRaisingEvents = true;
addlistener(file,'Changed',@eventhandlerChanged);
% ---------------------------------------------------------------
% I would like to be able to output the variables x,y,z from
% eventhandlerChanged, to use here, e.g.
total = x + y + z;
% ---------------------------------------------------------------
function eventhandlerChanged(source,arg)
% Open and read text file
f_ID = fopen('c:\work\temp\text_file.txt','r');
txt_str = fscanf(f_ID,'%s');
% Text file contains a single line with format:
% 'x_value:y_value:z_value
% Split the string at the colons
x_y_z = strsplit(txt_str,':');
% ---------------------------------------------------------------
% These are the variables I would like to pass to the workspace:
x = str2double(x_y_z(1));
y = str2double(x_y_z(3));
z = str2double(x_y_z(5));
% ---------------------------------------------------------------
end
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre Environment and Settings en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!