I want to make a function in which it takes 2 Input argument (polynomial order n , polynomial coefficient vector ) and gives the output polynomial equation f(x). Also, In the function i take input values of x and my function gives output values of f

5 次查看(过去 30 天)
function poly(n,V)
syms x
f(x)=V(1)*(x^0);
for i=n:-1:1
f(x)=V(i+1)*(x^i)+f(x);
end
f(x)
s=input('values of x :');
f(s)
end
It doesn't give right answer. any other method then please suggest.
  5 个评论
Vipul Kumar
Vipul Kumar 2018-8-26
n is a single integer which represents order of polynomial and V is a row vector or array which represent coefficient of polynomial. example- for x^2+2*x+3 ; n=2 and V=[3,2,1]

请先登录,再进行评论。

回答(2 个)

dpb
dpb 2018-8-25
编辑:dpb 2018-8-26
function [y fn]=poly(V,x)
y=polyval(V,x); % return values for inputs
n=length(V); % length of coeff vector determines order
trms=[V;[n-1:-1:0]]; % terms to write to functional
trms=trms(:); trms=trms(1:end); % don't write out x^0
fmt=[repmat('%d*x.^%d+',1,n-1) ,'%d']; % format string to build polynomial
fn=sprintf(fmt,trms);
end
Retrurns the polynomial string as string; not sure what end use is to be for...if the thought is it is needed to do a polynomial evaluation given the coefficient vector, then there's no need for it at all (or the function), just use polyval directly.
If there's some other purpose (like for display) then the string should suffice altho might use the new string class or a cellstr instead of just char string array.
If it is wanted to make a functional, then modify slightly--
fmt=['@(x)' repmat('%d*x.^%d+',1,n-1) ,'%d'];
fn=str2func(sprintf(fmt,trms))
fn =
function_handle with value:
@(x)1*x.^2+2*x.^1+3
fn(1:3)
ans =
6 11 18
To compare...
polyval(1:3,1:3)
ans =
6 11 18

Dimitris Kalogiros
Dimitris Kalogiros 2018-8-25
编辑:Dimitris Kalogiros 2018-8-25
clear; clc; close all;
V_example=[3 4 5 6 7 ];
n_example=length(V_example)-1;
y=my_poly(n_example, V_example)
%... Function definition...
function y=my_poly(n,V)
syms x
f(x)=V(1)*(x^0);
for i=n:-1:1
f(x)=V(i+1)*(x^i)+f(x);
end
f(x)
s=input('values of x :');
y=f(s);
end

类别

Help CenterFile Exchange 中查找有关 Polynomials 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by