如何在 MATLAB 中使用计时器以固定时间间隔运行函数

2024-01-09

我想以 30 分钟的间隔运行一个函数。每次运行该函数时,都会采用不同的输入。假设我想运行 100 次。函数为lookupweather,输入为location1、location2、location3、...、location100

我试过了:

for a = 1:100
    t = timer;          
    t.StartDelay = 30*60*(a-1)       
    t.TimerFcn = @(scr, event) run('lookupweather');
    start(t)
end 

这里的问题是我找不到输入位置信息的地方。如果我尝试了一些lookupweather(location1),代码就会失败。当然,如果没有位置输入,lookupweather 函数就会失败。有人可以帮忙吗?

编辑:我意识到我可以做固定间隔

t = timer;
t.Period = 30*60;
t.TasksToExecute = 100;
t.ExecutionMode = 'fixedRate';
t.TimerFcn = @(src, event) run('lookupweather');
start(t)

不过,我仍然不知道如何将位置信息输入到我的函数 Lookupweather 中。


您需要使用元胞数组声明计时器回调函数,如下所示:

location_index = 1;

t = timer;
t.Period = 1;  %30*60;
t.TasksToExecute = 5;  %100;
t.ExecutionMode = 'fixedRate';
t.TimerFcn = {@timer_callback, location_index};
start(t);

process_locations = true;
while process_locations
    % . . . 
end
stop(t);
delete(t);

function timer_callback(obj, event, location_index)
    fprintf("Location index = %03d\n", location_index);
end

您可能还需要使用位置的一维向量(或数组),如下所示:

locations = zeros(1, 100);

t = timer;
t.Period = 1;  %30 * 60;
t.TasksToExecute = 5;  %100;
t.ExecutionMode = 'fixedRate';
%t.TimerFcn = {@timer_callback2};
t.TimerFcn = {@timer_callback3, locations};
start(t);

process_locations = true;
while process_locations
    % . . . 
end
stop(t);
delete(t);

function timer_callback2(obj, event)
    persistent location_index;
    if isempty(location_index)
        location_index = 1;
    end
    fprintf("Location index = %03d\n", location_index);
    location_index = location_index + 1;
end

function timer_callback3(obj, event, locations)
    persistent location_index
    if isempty(location_index)
        location_index = 1;
    end
    locations(location_index) = 12.3;  % Get value from temperature sensor.
    fprintf("locations(%03d) = %f\n", location_index, locations(location_index));
    location_index = location_index + 1;
end

版本4

这使用了在计时器回调中修改的全局结构。考虑将其封装在处理程序类或嵌套函数中以避免使用全局变量。

clear all;
clc;

number_of_iterations = 10;  % 100
number_of_locations = 5;

% Create a global struct for the data.
% Consider encapsulating in a class rather than using a global.
global temperature_data;
temperature_data = struct("IterationIndex", 1, "Processed", false, "Locations", zeros(number_of_iterations, number_of_locations));

t = timer;
t.Period = 1;  %30 * 60;
t.TasksToExecute = number_of_iterations;
t.ExecutionMode = 'fixedRate';
t.TimerFcn = {@TimerCallback4};
start(t);
while temperature_data.Processed == false
        % . . .
        % Yield some processing time.
        time_delay = t.Period * 1000 / 10;
        java.lang.Thread.sleep(time_delay);
end
stop(t);
delete(t);

function TimerCallback4(obj, event)
    global temperature_data;

    % Cycle through locations.
    for location_index = 1:5
        % Get value from temperature sensor.
        temperature_data.Locations(temperature_data.IterationIndex, location_index) = 100 * rand;
        fprintf("temperature_data(%03d, %d) = %5.2f\n", temperature_data.IterationIndex, location_index, temperature_data.Locations(temperature_data.IterationIndex, location_index));
    end

    % Test for completion of processing.
    if temperature_data.IterationIndex >= size(temperature_data.Locations, 1)
        temperature_data.Processed = true;
    else
        temperature_data.IterationIndex = temperature_data.IterationIndex + 1;
    end
end

第 4 版结果

TimerCallback4() 0.058
TimerCallback4() 1.023
TimerCallback4() 2.033
TimerCallback4() 3.042
TimerCallback4() 3.961
TimerCallback4() 4.975
TimerCallback4() 5.982
TimerCallback4() 6.990
TimerCallback4() 8.002
TimerCallback4() 9.008
   10.7889   18.2228    9.9095   48.9764   19.3245
   89.5892    9.9090    4.4166   55.7295   77.2495
   31.1940   17.8982   33.8956   21.0146   51.0153
   90.6364   62.8924   10.1534   39.0855    5.4617
   50.1283   43.1721   99.7560   81.1603   48.5652
   89.4448   13.7547   39.0005   92.7356   91.7494
   71.3574   61.8337   34.3288   93.6027   12.4774
   73.0585   64.6477   83.3152   39.8282   74.9822
   83.5221   32.2460   55.2262   97.9129   54.9309
   33.0424   61.9472   36.0637   75.6510   41.3901

版本5

该版本使用句柄类。它可以同步或异步处理。

Test.m

    clear all;
    clc;

    % Define the settings.
    number_of_iterations = 10;  % 100
    number_of_locations = 5;
    period = 1;  % 30 * 60  % Seconds.

    % Create the object with required settings.
    temperature_processor = TemperatureProcessor(number_of_iterations, number_of_locations, period);

    % Do the process synchronously.
    temperature_processor.ProcessSync();
    disp(temperature_processor.Locations);

    % Do the process asynchronously.
    temperature_processor.IsProcessed = false;
    temperature_processor.ProcessAsync();
    while temperature_processor.IsProcessed == false
        % Do other stuff.
        % . . .

        % Yield some processing time.
        %pause(0.001);
        java.lang.Thread.sleep(1);  % milliseconds.
    end
    disp(temperature_processor.Locations);

    % Delete the object.
    delete(temperature_processor);

温度处理器.m

    classdef TemperatureProcessor < handle

        properties
            IsProcessed = false;
            Locations;
        end

        properties (Access = private)
            % Define default values.
            NumberOfIterations = 100;
            NumberOfLocations = 5;
            Period = 30 * 60;  % Seconds.
            AsyncIterationIndex = 1;
            AsyncTimer;
        end

        methods
            % Constructor.
            function obj = TemperatureProcessor(number_of_iterations, number_of_locations, period)
                fprintf("obj.TemperatureProcessor() constructor\n");

                if nargin == 3
                    obj.NumberOfIterations = number_of_iterations;
                    obj.NumberOfLocations = number_of_locations;
                    obj.Period = period;
                end
                obj.Locations = zeros(obj.NumberOfIterations, obj.NumberOfLocations);
            end

            % Destructor.
            function delete(obj)
                fprintf("obj.delete() destructor\n");
                try
                    stop(obj.AsyncTimer);
                    delete(obj.AsyncTimer);
                catch
                end
            end

            function ProcessSync(obj)
                fprintf("obj.ProcessSync()\n");

                iteration_index = 1;
                the_timer = timer;
                the_timer.Period = obj.Period;
                the_timer.TasksToExecute = obj.NumberOfIterations;
                the_timer.ExecutionMode = 'fixedRate';
                the_timer.TimerFcn = {@TimerCallbackSync};
                tic;
                start(the_timer);
                wait(the_timer);
                delete(the_timer);

                function TimerCallbackSync(timer_obj, timer_event)
                    fprintf("obj.Process.TimerCallbackSync() %0.3f\n", toc);

                    % Cycle through locations.
                    for location_index = 1:obj.NumberOfLocations
                        % Get value from temperature sensor.
                        obj.Locations(iteration_index, location_index) = 100 * rand;
                        fprintf("obj.Locations(%03d, %d) = %5.2f\n", iteration_index, location_index, obj.Locations(iteration_index, location_index));
                    end

                    % Test for completion of processing.
                    if iteration_index >= obj.NumberOfIterations
                        obj.IsProcessed = true;
                    else
                        iteration_index = iteration_index + 1;
                    end
                end
            end

            function ProcessAsync(obj)
                fprintf("obj.ProcessAsync()\n");

                try
                    stop(obj.AsyncTimer);
                    delete(obj.AsyncTimer);
                catch
                end
                obj.AsyncIterationIndex = 1;
                obj.AsyncTimer = timer;
                obj.AsyncTimer.Period = obj.Period;
                obj.AsyncTimer.TasksToExecute = obj.NumberOfIterations;
                obj.AsyncTimer.ExecutionMode = 'fixedRate';
                obj.AsyncTimer.TimerFcn = {@obj.TimerCallbackAsync};
                tic;
                start(obj.AsyncTimer);
            end

            function TimerCallbackAsync(obj, timer_obj, timer_event)
                fprintf("obj.Process.TimerCallbackAsync() %0.3f\n", toc);

                % Cycle through locations.
                for location_index = 1:obj.NumberOfLocations
                    % Get value from temperature sensor.
                    obj.Locations(obj.AsyncIterationIndex, location_index) = 100 * rand;
                    fprintf("obj.Locations(%03d, %d) = %5.2f\n", obj.AsyncIterationIndex, location_index, obj.Locations(obj.AsyncIterationIndex, location_index));
                end

                % Test for completion of processing.
                if obj.AsyncIterationIndex >= obj.NumberOfIterations
                    try
                        stop(obj.AsyncTimer);
                        delete(obj.AsyncTimer);
                    catch
                    end
                    obj.IsProcessed = true;
                else
                    obj.AsyncIterationIndex = obj.AsyncIterationIndex + 1;
                end
            end
        end
    end

版本 5 结果

obj.TemperatureProcessor() constructor
obj.ProcessSync()
obj.Process.TimerCallbackSync() 0.051
obj.Process.TimerCallbackSync() 1.029
obj.Process.TimerCallbackSync() 2.026
obj.Process.TimerCallbackSync() 3.025
obj.Process.TimerCallbackSync() 4.034
obj.Process.TimerCallbackSync() 5.024
obj.Process.TimerCallbackSync() 6.023
obj.Process.TimerCallbackSync() 7.023
obj.Process.TimerCallbackSync() 8.023
obj.Process.TimerCallbackSync() 9.023
obj.ProcessAsync()
obj.Process.TimerCallbackAsync() 0.009
obj.Process.TimerCallbackAsync() 1.005
obj.Process.TimerCallbackAsync() 2.004
obj.Process.TimerCallbackAsync() 3.005
obj.Process.TimerCallbackAsync() 4.007
obj.Process.TimerCallbackAsync() 5.005
obj.Process.TimerCallbackAsync() 6.005
obj.Process.TimerCallbackAsync() 7.005
obj.Process.TimerCallbackAsync() 8.005
obj.Process.TimerCallbackAsync() 9.005
obj.delete() destructor
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 MATLAB 中使用计时器以固定时间间隔运行函数 的相关文章

  • 无法取消 GWT 中的重复计时器

    我正在尝试在 GWT 中安排一个重复计时器 它将每一毫秒运行一次 轮询某个事件 如果发现满意 则执行某些操作并取消计时器 我尝试这样做 final Timer t new Timer public void run if condition
  • 将自动生成的 Matlab 文档导出为 html

    我想为我开发的 Matlab 工具箱生成完整的帮助 我已经看到如何显示自定义文档 http www mathworks fr fr help matlab matlab prog display custom documentation h
  • MATLAB 中最有效的矩阵求逆

    在 MATLAB 中计算某个方阵 A 的逆矩阵时 使用 Ai inv A should be the same as Ai A 1 MATLAB 通常会通知我这不是最有效的求逆方法 那么什么是更有效率的呢 如果我有一个方程系统 可能会使用
  • Simulink 仿真引擎如何工作?

    我想了解 Simulink 仿真引擎的工作原理 它是否使用离散事件模拟机制 那么如何处理连续时间 它是否依赖于基于静态循环的代码生成 或者 在第一个周期之前 它会计算出块的执行顺序 从不需要任何其他块输入的块开始 每个周期 它都会根据输入和
  • 制作一个“任意键”可中断的 Python 定时器

    我正在尝试制作一个简单的计时器 它会一直计时 直到被键盘输入中断 现在我正在使用 CTRL C 来停止计时器 但我想做一些更简单的事情 例如按空格或 Enter 或 任意键 我听说这可以通过线程模块来完成 但经过几次尝试后 我显然不知道我在
  • 如何使用Java.Util.Timer

    我想制作一个简单的程序 使用 Java Util Timer 计算秒数直到 100 下面的代码是我正在使用的代码 但是它只是立即打印出所有数字 而无需在每个数字之间等待一秒钟 我该如何解决这个问题 通常我会使用 thread sleep 但
  • MATLAB:具有复数的 printmat

    我想使用 MATLAB 的printmat显示带有标签的矩阵 但这不适用于复数 N 5 x rand N 1 y rand N 1 z x 1i y printmat x y z fftdemo N 1 2 3 4 5 x y x iy O
  • 如何在 Matlab 中将数组打印到 .txt 文件?

    我才刚刚开始学习Matlab 所以这个问题可能非常基本 我有一个变量 a 2 3 3 422 6 121 9 4 55 我希望将值输出到 txt 文件 如下所示 2 3 3 422 6 121 9 4 55 我怎样才能做到这一点 fid f
  • 如何将二进制值列表转换为int32类型?

    我在 MATLAB 工作区中有一个小端格式的二进制数列表 我想将它们转换为 int32 a是由 0 和 1 组成的双向量 如下所示 a 0 0 0 1 1 0 0 1 1 1 1 0 1 0 1 0 0 0 0 1 1 0 0 0 1 1
  • Android 中的计时器任务在无限期时间后停止运行

    我是安卓新手 我正在开发一个应用程序 其中一段特定的代码在后台每 5 秒后执行一次 为了实现这一目标 我使用带有定时器的服务 其中包含定时器任务 有时它工作正常 但经过一段时间后 我的服务正在运行 但计时器任务在 android 中自动停止
  • 括号中的波形符字符

    在 MATLAB 中 以下代码执行什么操作 m func returning matrix 波浪号运算符 的作用是什么 在 Matlab 中 这意味着不要将函数中相应的输出参数分配到赋值的右侧 因此 如果func returning mat
  • 黑白随机着色的六角格子

    我正在尝试绘制一个 10 000 x 10 000 随机半黑半白的六边形格子 我不知道如何将该格子的六边形随机填充为黑色和白色 这是我真正想要从这段代码中得到的示例 但我无法做到 https i stack imgur com RkdCw
  • Python:threading.timer不尊重间隔

    这是后续另一个问题 https stackoverflow com questions 32286049 python accept input while waiting 我现在有了一个解决方案 但由于不相关的原因 实现似乎没有正常运行
  • Python 日志记录中的准确时间戳

    我最近一直在构建一个错误日志应用程序 并且正在寻找一种准确地为传入数据添加时间戳的方法 当我说准确时 我的意思是每个时间戳相对于彼此应该是准确的 不需要同步到原子钟或类似的东西 我一直在使用 datetime now 作为第一次尝试 但这并
  • matlab中的正则逻辑回归代码

    我正在尝试正则化 LR 在 matlab 中使用以下公式很简单 成本函数 J theta 1 m sum y i log h x i 1 y i log 1 h x i lambda 2 m sum theta j 梯度 J theta t
  • 检测植物图片中的所有分支

    我想知道有什么可以检测下图中的所有绿色树枝 目前我开始应用 Frangi 过滤器 options struct FrangiScaleRange 5 5 FrangiScaleRatio 1 FrangiBetaOne 1 FrangiBe
  • 访问图像的 Windows“标签”元数据字段

    我正在尝试进行一些图像处理 所以现在我正在尝试读取图像 exif 数据 有 2 个内置函数可用于读取图像的 exif 数据 问题是我想读取图像标签 exifread and imfinfo这两个函数都不显示图像标签 Is there any
  • 如何在 MATLAB 中绘制 3D 曲面图?

    我有一个像这样的数据集 0 1 0 2 0 3 0 4 1 10 11 12 13 2 11 12 13 14 3 12 13 14 15 4 13 14 15 16 我想在 matlab 中绘制 3D 曲面图 使列标题位于 y 轴 行标题
  • 在 AS3 中创建一个(适当的)计时器

    如何在as3中创建时间计数器 在 google 上进行一些简单的搜索 您会找到 AS3 类 Timer 它实际上是事件计数器 不是一个合适的时间计数效用 我见过这个http blogs adobe com pdehaan 2006 07 u
  • glpk.LPX 向后兼容性?

    较新版本的glpk没有LPXapi 旧包需要它 我如何使用旧包 例如COBRA http opencobra sourceforge net openCOBRA Welcome html 与较新版本的glpk 注意COBRA适用于 MATL

随机推荐