matlabcontinued-fractions

Matlab code for continued fraction


I want to use continued fraction for digital watermarking. I need to evaluate a number using the concept of continued fraction. Can anyone provide the matlab code for continued fractions?


Solution

  • You can use the rat function:

    >> rat(0.23)
    
    ans =
    
    0 + 1/(4 + 1/(3 + 1/(-8)))
    

    The output of this function is a string. If you want to parse this output, you can refer to this topic.

    Edit:

    If you want to have only positive numbers in the resulting expansion, then you can achieve this through editing rat.m (edit rat.m). See this topic.

    Basically, you need to change line 100 of rat.m from d = round(x) to d = floor(x). If you don't want to change the Matlab sources, you can save a copy of the new rat.m somewhere and even change the name of the function if you'd like.

    With the modified rat function:

    >> rat(0.23)
    
    ans =
    
    0 + 1/(4 + 1/(2 + 1/(1 + 1/(7))))