필터 지우기
필터 지우기

how can I set the decimal digits of all coefficients at one time when outputting a polynomial f?

조회 수: 2 (최근 30일)
In Windows 10, MATLAB R2018a, I try to use fprintf to output a polynomial f, for example, 5.327416*x^2+3.660092*x+1.5799301. How can I set the decimal digits(e.g. 3) of all coefficients at one time instead of setting them one by one? That is, I want the result to be "5.327*x^2+3.660*x+1.580". Anyone can help me? Thanks!

채택된 답변

Walter Roberson
Walter Roberson 2023년 10월 27일
P = [5.327416, -3.660092, 1.5799301]
P = 1×3
5.3274 -3.6601 1.5799
%method 1
vpa(poly2sym(P, sym('x')),4)
ans = 
%method 2
poly2sym(round(sym(P),3))
ans = 
%method 3
fmt = [repmat('%.3f*x^%d + ', 1, length(P)-1), '%.3f\n'];
temp = reshape([P; length(P)-1:-1:0], 1, []);
fprintf(fmt, temp(1:end-1));
5.327*x^2 + -3.660*x^1 + 1.580
If you want the + -3.660 to instead show up as - 3.660 then it takes more work.
  댓글 수: 3
Dyuman Joshi
Dyuman Joshi 2023년 10월 27일
편집: Dyuman Joshi 2023년 10월 27일
You can use disp on the symbolic expression or convert it to char and use fprintf as well -
P = [5.327416, -3.660092, 1.5799301]
P = 1×3
5.3274 -3.6601 1.5799
y = vpa(poly2sym(P, sym('x')),4);
disp(y)
z = char(y);
fprintf('%s', z)
5.327*x^2 - 3.66*x + 1.58

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

추가 답변 (1개)

Sam Chak
Sam Chak 2023년 10월 27일
a = 5.327416;
b = 3.660092;
c = 1.5799301;
fprintf('f(x) = %.3f*x^2 + %.3f*x + %.3f', a, b, c)
f(x) = 5.327*x^2 + 3.660*x + 1.580
  댓글 수: 1
marvellous
marvellous 2023년 10월 27일
Thank you for your help, but this is not what I want. Since I may not know the degree of f, I can not write out the 'x' items in advance. Thus, I do not intend to set the decimal digit for each coefficient separately. I prefer to write like ' fprintf (' ? ' , f) ', but I can not figure out what to fill in at the question mark to make it work? Can you help me?

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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by