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일)
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 CenterFile Exchange에서 Polynomials에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by