如何在 Matlab 中执行代码期间保持变量的恒定值

How to keep a constant value of a variable during the execution of the code in Matlab

我有一个关于在 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" 时如何保持 "Offset" 的计算值。由于我们在开始时有一个 "for" 循环(它将一个值分配给 K,然后分配给 Offset),所以我只需要在 HmSpeedReached 条件之后一直将该数字作为变量的值很满意... 提前谢谢你。

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

如果我没理解错,那么你想要的是:

  • 在遍历代码时继续分配 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