How can I display on a plot's Title the input value pi with Greek character "π" or in English "pi". For example: prompt = 'What is the original value? '; x = input(prompt) I insert the value pi/2 So i want the plot title to be like: Output=π/2 I used the following code but it keeps giving me the value 0.707 instead of the π/2 or pi/2 i want.
str = sprintf('Output x=%d',x);
title(str);

 채택된 답변

Kirby Fears
Kirby Fears 2015년 12월 23일
편집: Kirby Fears 2015년 12월 23일

1 개 추천

x is a double-precision floating point number. It will be displayed as a decimal by default. You can control how the double is represented (like scientific notation), but there is no built-in ability to display a double in terms of pi multiples. You're specifically trying to represent x in terms of pi/n for the appropriate n value.
Use the '\pi' character to display the symbol for pi. Calculate the value n = pi/x to build the expression "x = pi/n" in the title.
str = sprintf('Output x=%s/%d','\pi',pi/x);
title(str);

댓글 수: 4

Nick Papanikolaou
Nick Papanikolaou 2015년 12월 23일
Thank you very much.But it seems it can't display correct the x=3Π/4 value. It gives π/1
Am I doing something wrong?
Kirby Fears
Kirby Fears 2015년 12월 24일
편집: Kirby Fears 2015년 12월 24일
Here's another approach using rats() to generate a rational approximation of the fraction of pi:
x = pi * 3/4;
R = strtrim(rats(x/pi));
str = sprintf('Output x=%s*%s','\pi',R);
% plot(...);
title(str);
Kirby Fears
Kirby Fears 2015년 12월 24일
편집: Kirby Fears 2015년 12월 24일
To make it look really nice, you'll need a bit of case handling to insert \pi into the proper position.
x = pi * 3/4;
R = strtrim(rats(x/pi));
idxFrac = strfind(R,'/');
if isempty(idxFrac),
if strcmp(R,'0'),
fracStr = '0';
elseif strcmp(R,'1'),
fracStr = '\pi';
elseif strcmp(R,'-1'),
fracStr = '-\pi';
else
fracStr = [R,'\pi'];
end
else
leftStr = R(1:idxFrac-1);
rightStr = R(idxFrac:end);
if strcmp(leftStr,'1'),
fracStr = ['\pi' rightStr];
elseif strcmp(leftStr,'-1'),
fracStr = ['-\pi' rightStr];
else
fracStr = [leftStr '\pi' rightStr];
end
end
titleStr = sprintf('Output x = %s',fracStr);
% plot(...);
title(titleStr);
DEBARSHI MAJUMDER
DEBARSHI MAJUMDER 2020년 3월 11일

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Labels and Annotations에 대해 자세히 알아보기

질문:

2015년 12월 23일

댓글:

2020년 3월 11일

Community Treasure Hunt

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

Start Hunting!

Translated by