我有一个关于在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的条件后始终将该数字保留为变量的值... 提前谢谢。
答案 0 :(得分:0)
在顶部指定HmSpeedReached = 0并测试HmSpeedReached等于零作为更改变量Offset的条件。
答案 1 :(得分:0)
如果我理解正确,那么您需要以下内容:
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