【问题标题】:How to keep a constant value of a variable during the execution of the code in Matlab如何在 Matlab 中执行代码期间保持变量的恒定值
【发布时间】:2017-03-09 22:31:29
【问题描述】:

我有一个关于在 Matlab 代码中操作变量的简短问题(我认为也很愚蠢)。如何在代码进一步执行时保持变量的恒定值(在代码执行期间分配)?所以基本上把值放到内存中,不要全部改变。作为我现在正在处理的代码示例:

 if SystemTriggered ==1;     
   if Accelerationflag == 1;
     for n = 1:1:100
         AOrder = 1/2*HMSpeed^2/(Acc+n*2*pi);
            if AOrder<Alim;
                k = n;
                Accelerationflag = 0;
                break;
            end
        end
    end
    Offset = k;
    AccOffset = PhaseIni - Offset*2*pi;
    %Derivation conditions
    if My condition here;
        HmSpeedReached = 1;
    end
  end

所以我正在寻找一个选项,当我得到“HmSpeedReached =1”时,如何保持“偏移”的计算值。由于我们在开始时有一个“for”循环(它将为 K 分配一个值,然后为 Offset 分配一个值),所以在满足 HmSpeedReached 的条件后,我只需将该数字始终作为变量的值... 提前谢谢你。

【问题讨论】:

  • 您是否考虑过使用向量将值分配给与当前迭代匹配的元素?或者,如果您想确保它们在程序终止后仍然存在,您可以将这些值附加到日志文件中。
  • 感谢您的宝贵时间。好吧,我可以使用日志文件。但我也可以通过使用一些 Simulink 模块轻松获得所需的“偏移”值。但就我而言,我正在寻找一个选项,如何在执行时保持“偏移”的值。由于 Simulink 模型的性质(代码是其中的一部分),循环“for”可以再次执行,所以在我们得到 HmSpeedReached = 1 后它会覆盖“Offset”的值。抱歉我没有指定问题中是否存在 Simulink 模型。

标签: matlab variables constants cycle execution


【解决方案1】:

如果我理解正确,那么您需要以下内容:

  • 在循环访问您的代码时继续分配Offset = k
  • 如果已设置HmSpeedReached = 1,则不要更改Offset

这段代码(改编自你的)应该可以工作

% Initially make sure HmSpeedReached is not equal to 1
HmSpeedReached = 0;
% Your code with addition...
if SystemTriggered ==1;     
   if Accelerationflag == 1;
       for n = 1:1:100
           AOrder = 1/2*HMSpeed^2/(Acc+n*2*pi);
           if AOrder<Alim;
               k = n;
               Accelerationflag = 0;
               break;
           end
       end
    end
    % Add a condition here to check if Offset should be updated, if HmSpeedReached is not 1
    if HmSpeedReached ~= 1
        Offset = k;
    end 

    AccOffset = PhaseIni - Offset*2*pi;
    %Derivation conditions
    if My condition here;
      HmSpeedReached = 1;
    end
end

如果您想保存Offset 值的向量,则每次满足某些条件时,请使用以下内容:

Offset = [];
HmSpeedReached = 0;
if SystemTriggered ==1;     
    if Accelerationflag == 1;
        for n = 1:1:100
            AOrder = 1/2*HMSpeed^2/(Acc+n*2*pi);
            if AOrder<Alim;
                k = n;
                Accelerationflag = 0;
                break;
            end
        end
    end
    % Add a condition here to check if Offset should be updated, if HmSpeedReached is not 1
    if CONDITION FOR SAVING OFFSET
        Offset = [Offset, k];
    end 

    AccOffset = PhaseIni - Offset*2*pi;
    %Derivation conditions
    if My condition here;
        HmSpeedReached = 1;
    end
end

【讨论】:

  • 非常感谢!正如我所想,这将是一个简单的解决方案。我检查了第一个修改过的代码,它工作得很好。
【解决方案2】:

在顶部指定 HmSpeedReached = 0 并测试 HmSpeedReached 是否等于 0 作为更改变量 Offset 的条件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-15
    • 1970-01-01
    • 2020-09-21
    • 2017-01-16
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    相关资源
    最近更新 更多