rats

Rational output: a number formatted as a fraction in a string.

Category: Mathematics > Elementary Math

Syntax

s = rats(X)

Returns a character vector showing each element of X as a ratio of integers.

s = rats(X, strlen)

Limits the width of each field to strlen characters (default 13).

Description

rats(0.75) gives 3/4 surrounded by blanks. The approximation is found by continued fractions, with as large a denominator as the field width allows, so rats(pi) gives 355/113. Elements with no good short ratio are shown as the closest fraction that fits.

The same display is produced by format rat when printing matrices. Because the string is padded, use strtrim if the exact text is needed.

Input arguments

X
Real numeric array.
strlen
Maximum field width. A narrower width forces a coarser fraction.

Output arguments

s
Character vector, padded with blanks on both sides of each fraction.

Example

Fractions and field width

strtrim(rats(0.75))
strtrim(rats(pi))
strtrim(rats(pi, 8))
Output
ans = '3/4'
ans = '355/113'
ans = '355/113'

See also

rat format strtrim num2str