Doug's MATLAB Video Tutorials

January 8th, 2010

Basics: Refactoring a switchyard into a formula

This short video shows how a switchyard of if/elseif statements was converted to a simple formula. Testing of this refactoring was also done.

3 Responses to “Basics: Refactoring a switchyard into a formula”

  1. Han Geerligs replied on :

    Hi Doug,

    how about the behaviour of your function for input between a multiple of hundred and that value+1?
    As an example: the original code doesn’t assign a value to OutVal for val=100.5. Your refactored code assigns a value OutVal=100 to it.

    –Han

  2. dhull replied on :

    Han,

    Good find! I do not know what the intentions of the original author were. I suspect that was an error in the original implementation, though we never discussed it. They may have also assumed integer input.

    Doug

  3. Zane replied on :

    I remember coming up with this method for one of the ol’ Monday Math Madnesses. You can use floor(Val/100), etc to extract digits from a multidigit number after subtracting out higher orders. It’s not entirely refactoring because I didn’t find anyway to do it before, but uses a similar concept.

    Input=485;
    dig(1)=floor(Input/100);
    dig(2)=floor(Input/10)-dig(1)*10;
    dig(3)=floor(Input)-dig(1)*100-dig(2)*10;
    

    careful indexing could be applied to scale for much larger numbers.

Leave a Reply

Wrap code fragments inside <pre> tags, like this:

<pre class="code">
a = magic(3);
sum(a)
</pre>

If you have a "<" character in your code, either follow it with a space or replace it with "&lt;" (including the semicolon).


MathWorks

Doug Hull is a proud MathWorker who is on a mission to help you with MATLAB.

Doug's picture

These postings are the author's and don't necessarily represent the opinions of The MathWorks.