Convert a string containing a fraction into a number in a fraction format

22 views (last 30 days)
I need to convert a string containing a fraction (for example, x='4/5') into a number. Every time I do this, the fraction is evaluated and the answer is always x=.8, but I need the number to stay as a fraction. I can't use the rats function, because I need to be a number (I'm multiplying it with another number). Is there a way I can keep x in a fraction format--or convert it from a decimal to a fraction if that's not possible?

Answers (3)

Akira Agata
Akira Agata on 18 Jan 2018
if your string is always '(numbers)/(numbers)' format, the numerator and denominator of the fraction can be extracted by using regexp function. Here is an example.
str = '423/523';
c = regexp(str,'[0-9]+','match');
numerator = str2double(c{1});
denominator = str2double(c{2});

Stephen23
Stephen23 on 19 Jan 2018
Edited: Stephen23 on 19 Jan 2018
Much simpler and faster is to use sscanf and simple two-element numeric vectors to represent the fractions:
>> x = sscanf('6/4','%d/%d')
x =
6
4
>> y = x .* [5;1] % x * 5/1
y =
30
4
>> z = x .* y % 6/4 * 30/4
z =
180
16
Finding the lowest terms fraction is easy using gcd (compare Steven Lord's answer):
>> z / gcd(z(1),z(2))
ans =
45
4
As is getting the (possibly approximately) equivalent decimal fraction:
>> z(1)/z(2)
ans = 11.250
Thus you get to trivially avoid the pointless complexity and slowness of using symbolic toolbox, and can use basic mathematical operations on the numerator or denominator, or both together.

Steven Lord
Steven Lord on 18 Jan 2018
You could convert it into a symbolic variable. However be aware that the fraction contained in the symbolic variable may be equivalent but not identical to the fraction written in the string, as the x variable created in the example below shows.
>> s = '6/4';
>> x = sym(s)
x =
3/2
>> y = 5*x
y =
15/2
>> z = x*y
z =
45/4

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!