I am implementing a logarithmic quantizer which is defined as follows:

$$ q(u) = \begin{cases} u_i , \frac{u_i}{1+\delta} < u < \frac{u_i}{1-\delta} \\ 0 , 0 \leq u \leq \frac{u_o}{1+\delta} \\ -q(-u), \ u < 0 \end{cases} $$

where the different parameters are computed based upon these expressions:

$$ u_i = p^{1-i}u_o, \ i = 1,2,\dots $$ $$ \delta = \frac{1-p}{1+p} $$ $$ u_{min} = \frac{u_o}{1+\delta} $$

More information regarding the quantizer can be found at this paper: Adaptive Backstepping Control of Uncertain Nonlinear Systems with Input Quantization.

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;
        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;
            i = i + 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 should go away and be replaced. Any thoughts would be really appreciated.

  • 1
    $\begingroup$ This is not really what this particular StackExchange forum is there for: Optimize code. But separately, before you optimize, what is your evidence that the code as is is actually problematic and needs to be optimized? $\endgroup$ – Wolfgang Bangerth Feb 5 at 17:46
  • $\begingroup$ Yes, I know about the particular forum but I had to include equations and stackoverflow doesn't allow MathJax at all, as far as I know. Code works but this kind of infinite loop being broken at some time, isn't a good programming technique. That is why I would like some advice. $\endgroup$ – Teo Protoulis Feb 5 at 17:57
  • $\begingroup$ You can include formulas by delimiting them with dollar signs, as usual in LaTeX. If your goal is just advise on how to program, or improve code, there is a whole StackExchange forum for just that. $\endgroup$ – Wolfgang Bangerth Feb 5 at 19:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.