Updated 2 May 2017
The fractions toolbox allows users to create and manipulate fractions and fraction arrays of the form K+N/D, e.g.
fr(1,3) % returns 1 / 3
fr(pi) % returns 3 + 4703 / 33215
All the standard arithmetic and comparison operations are valid:
fr(1,3)+fr(1,2) % returns 5 / 6
fr(1,3)>0.3 % returns 1
A = fr(ones(2),[2,3;5,7]);
B = fr(ones(2,1),[11;13]);
A\B % returns [-3+49/143; 4+37/143]
lsq(fr([1;1]),[0;1]) % returns 1/2
The treatment of singular and non-square systems is different from that of the built-in "\" so please read the documentation, e.g. for reasons of personal preference "\" does not do least-squares by default - use lsq instead.
Partial fractions and arbitrary-base digits can be computed:
[d,r]=digits(fr(1,7),4,3) % 4 digits of base-3 expansion of 1/7 plus remainder
% returns d=[0,1,0,2] and r= 4/567
Continued fractions expansions of fractions and square roots:
[cf,rep] = cfracsqrt(fr(13,5)) % continued fraction of sqrt(13/5)
[r1,r2] = bestrat(cf,rep,1000) % best rational approximations with denominator limit 1000
A powerful feature of the toolbox is that the numerator and denominator can theoretically be any data types that accept the standard arithmetic and comparison operations as well as gcd and mod. For example, if you have John D'Errico's Variable Precision Integer Toolbox (20 July 2009 release or later; see link below):
1 / 10575608481180064985917685760000000000
If there exists a suitably defined polynomial object, this toolbox could be used to perform partial fraction and series expansions of rational functions.
See the demo and help files for a full list of features.
The functions have been tested with doubles and vpi integers, but message me if you encounter any problems, and let me know how it goes with other data types.
Ben Petschel (2023). Fractions Toolbox (https://www.mathworks.com/matlabcentral/fileexchange/24878-fractions-toolbox), MATLAB Central File Exchange. Retrieved .
MATLAB Release Compatibility
Platform CompatibilityWindows macOS Linux
Inspired by: Variable Precision Integer Arithmetic
Inspired: The Computation of Pi by Archimedes
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!
Discover Live Editor
Create scripts with code, output, and formatted text in a single executable document.
Updated power (^) to allow negative exponents and added functions max, min, num2str.
Updated to work with recent versions of MATLAB and tidied up some of the code.
Improved performance of fr.m (thanks to Richard Zapor); bugfix in freduce.m affecting objects that do not have mrdivide defined (thanks to Nathan Thern); bugfix in frinv.m to allow rdivide with fraction arrays.
added rank function; bugfix for frinv handling non-double arrays
Improved performance of times and other operations; added functions for dealing with continued fractions
added functions mldivide (\), rref, lsq
fixed bug that can occur when users do not have the VPI toolbox.