matlabmatrixoctavelinear-algebra

Octave show fraction when dividing without calculating the decimal value


The calculation of 1/23 * [1 2 3] returns [0.041667 0.083333 0.125000].

I just want a display like [1/23 2/23 3/23]


Solution

  • You can specify format rat, to always display outputs as rational approximations (applies to both matlab and octave).

    format rat
    a = 1/23 * [1,2,3]
    % a = 1/23       2/23       3/23
    

    Or, you can use that "rat" or "rats" functions, to print (as strings) the rational approximations of a float array:

    a = 1/23 * [1,2,3]
    % a =    0.043478   0.086957   0.130435
    
    rats(a)
    % ans =  1/23       2/23       3/23
    

    As Cris pointed out in the comments, this is simply a representational issue. The underlying floating-point representation of the result does not change. If you wish to work with fractions in a 'mathematical' sense, then you need to go about this a different way (possibly symbolic package, or dealing with numerators and denominators manually).