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

6 ビュー (過去 30 日間)
Vipul Kumar
Vipul Kumar 2018 年 8 月 25 日
編集済み: dpb 2018 年 8 月 26 日
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 件のコメント
Dimitris Kalogiros
Dimitris Kalogiros 2018 年 8 月 25 日
As far as it concerns your example, what is the corresponding V factor ? V=[3 2 1] ?
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 Center および File ExchangePolynomials についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by