Kiteloopdesign
Kiteloopdesign

Reputation: 99

Displaying rational numbers in Matlab

I have two integer numbers m,n which together form a rational number in the form of m/n. Now I just want to display them in Matlab in this rational form.

I can do this by doing

char(sym(m/n))

So, if, e.g. m = 1, n = 2, Matlab will display 1/2. However, if m = 2, n = 4, I am also getting 1/2, whereas I want to get 2/4.

Any way of doing this without recurring to something like

fprintf( '%d/%d', m, n )

Thanks

Upvotes: 1

Views: 2021

Answers (1)

Mohsen Nosratinia
Mohsen Nosratinia

Reputation: 9864

You can change the display format to rat

>> format rat
>> 2/3
ans =
       2/3

otherwise you can call rats function

>> rats(2/3)
ans =
      2/3     
>> class(ans)
ans =
char

However, in both cases the fractions will be reduced. To avoid that you should create your separate function or introduce it as an anonymous function

>> rat2 = @(m,n) num2str([m n], '%d/%d')
rat2 = 
    @(m,n)num2str([m,n],'%d/%d')
>> rat2(2,4)
ans =
2/4

Upvotes: 4

Related Questions