Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

To resolve issues starting MATLAB on Mac OS X 10.10 (Yosemite) visit: http://www.mathworks.com/matlabcentral/answers/159016

Display rational numbers using fprintf

Asked by Qianyu on 4 Jan 2013

I am using fprintf to write my answers to a file. I have numbers such as: 3/7,3/11,6/37... I tried different formats but every time it always changed it to a numeric value. Then I tried format rat before fprintf. This didn't work neither. How can I display a rational number using fprintf?

0 Comments

Qianyu

Tags

Products

No products are associated with this question.

2 Answers

Answer by Matt Fig on 4 Jan 2013
Accepted answer
T = 1/3;
fprintf('The number is:  %s\n',strtrim(rats(T)))

1 Comment

Qianyu on 10 Jan 2013

Thanks. It worked great!

Matt Fig
Answer by Walter Roberson on 4 Jan 2013
[n,d] = rat(YourNumericValue);
fprint(fid, '%d/%d', n, d)

However, if you have the numerator and denominator already available, then

fprintf(fid, '%d/%d', numerator, denominator)

which is what I think you probably want to do, if I remember your earlier question properly.

MATLAB is not designed to be able to tell the difference between 3/4 and 6/8: it will calculate the binary equivalents of the result and use that binary result, except in the Symbolic Toolbox where it will reduce the fraction to lowest terms and use the reduced rational fraction.

0 Comments

Walter Roberson

Contact us