问题描述
我正在实现一个对数量化器,我想做的是尽可能地优化代码.我想进行更改的确切点是最后一个 else
语句,其中要实现的等式是:
I am implementing a logarithmic quantizer and what I would like to do is to optimize the code as much as possible. The precise point where I would like to make a change is the last else
statement where the equation to be implemented is:
q(u) = u_i
如果 u_i/(1+step)
u_i = p^(1-i)u_o
for i=1,2,...
参数p, step, u_o
是一些需要选择的常量.
The parameters p, step, u_o
are some constants to be chosen.
关于量化器的更多信息可以在这篇论文中找到:具有输入的不确定非线性系统的自适应反步控制量化.
More information regarding the quantizer can be found at this paper: Adaptive Backstepping Control of Uncertain Nonlinear Systems with Input Quantization.
为了在 MATLAB 中编写一个函数来实现它,我编写了以下代码:
In order to code a function to implement it in MATLAB, I wrote the following piece of code:
function q_u = logarithmic_hysteretic_quantizer(u,step,u_min)
u_o = u_min*(1+step);
p = (1-step)/(1+step);
if u < 0
q_u = -logarithmic_hysteretic_quantizer(-u,step,u_min);
elseif ( (u >= 0) && (u <= u_o/(1+step)) )
q_u = 0;
else
i = 1;
while (1)
u_i = p^(1-i) * u_o;
if ( (u > u_i/(1+step)) && (u <= u_i/(1-step)) )
q_u = u_i;
break;
end
i = i + 1;
end
end
end
现在,我的问题是尽可能地改进代码.例如,对不同量化级别进行编码的 while(1)
循环可能会消失并被替换.任何想法将不胜感激.
Now, my issue is to improve the code as much as I can. For example, the while(1)
loop, which codes the different quantization levels, is something that could probably go away and be replaced. Any thoughts would be really appreciated.
推荐答案
假设 u_min>0
和 0,你可以简化
(u> u_i/(1+step)) &&(u 到:
Assuming u_min>0
and 0<p<1
, you can simplify (u > u_i/(1+step)) && (u <= u_i/(1-step))
to:
u/u_min > p^(1-i) && p^-i >= u/u_min
由于 log
是单调的,所以简化为
Which since log
is monotonic, simplifies to
-log(u/u_min)/log(p) > i-1 && i >= -log(u/u_min)/log(p)
这使得while循环等价于简单
Which makes the while loop equivalent to simply
i = floor(-log(u/u_min)/log(p));
q_u = p^(1-i) * u_o;
此外,elseif
分支中的 (u >= 0)
总是为真,你可能可以去掉 u 测试,通过在正确的位置将
u
替换为 abs(u)
.
Furthermore, (u >= 0)
in the elseif
branch is always true, and you probably can get rid of the u<0
test, by replacing u
by abs(u)
at the right places.
这篇关于如何去除“无限"while 循环来改进 MATLAB 代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!