importing a csv file into matlab automatically after it gets changed
10 次查看(过去 30 天)
显示 更早的评论
I have .csv file on my desktop which get replaced. I want to use a command in matlab which imports this file every time it gets changed into matlab for calculations. I got this formula:
fsw = System.IO.FileSystemWatcher();
fsw.Path = 'C:\Users\wolfx\Desktop';
fsw.Filter = 'filename.csv';
fsw.EnableRaisingEvents = true;
listenerhandle = addlistener(fsw, 'Changed', importfcn);
%signature of importfcn is function importfcn(sender, eventargs)
%add a small delay in importfcn before reading the file as the event is raised
%to make sure that file modification is complete
This formula gives me the error Undefined function or variable 'importfcn'.
Can anyone give me a hint or a site where I can read more about this?
thanks
4 个评论
Geoff Hayes
2014-12-7
Isn't importfcn a function that you have created? In a previous post of yours, http://www.mathworks.com/matlabcentral/answers/163047-automatic-import-into-matlab-after-time-period, Guillame's answer included the following code
t = timer;
t.Period = 49 * 60;
t.TimerFcn = importfcn; %for you to define with signature: function
% importfcn(obj, event)
Note his comment - you have to define the function with the specified signature. Since you accepted his answer, then you must have created this file and so you must know which folder has it. So once you have found the file, you can add its folder to the search path in any number of ways, including using addpath.
采纳的回答
matt dash
2014-12-9
The errror is because when you just type "importfcn" it is attempting to RUN importfcn. What you're trying to do is tell the addlistener function "the NAME of the function i want you to run is "importfcn". You do this with the @ symbol. Thus you want:
listenerhandle = addlistener(fsw, 'Changed', @importfcn);
3 个评论
matt dash
2014-12-9
Ah, yes, that would be the "do something with the data" comment in Geoff's code above. If you're trying to send the data back to the base matlab workspace, look at the "assignin" function, which you can use in the importfcn variable to define a variable in the base workspace. E.g.
assignin('base','kevin',kevin)
更多回答(1 个)
Geoff Hayes
2014-12-7
AA - try creating a function as follows (saving this to file as importfcn.m or as a nested function within your other code)
function importfcn(obj, event)
% wait an extra second to ensure that the file modification is complete
pause(1.0);
% read the data from file
fileToRead = fullfile('C:\Users\wolfx\Desktop','filename.csv');
data = csvread(fileToRead);
% do something with the data
If you nest the function, then you can make use of fsw.Path and fsw.Filter in building the fileToRead and not have to hard-code the path and file name.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Import and Analysis 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!