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 visualizaciones (últimos 30 días)
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 comentarios
Dimitris Kalogiros
Dimitris Kalogiros el 25 de Ag. de 2018
As far as it concerns your example, what is the corresponding V factor ? V=[3 2 1] ?
Vipul Kumar
Vipul Kumar el 26 de Ag. de 2018
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]

Iniciar sesión para comentar.

Respuestas (2)

dpb
dpb el 25 de Ag. de 2018
Editada: dpb el 26 de Ag. de 2018
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 el 25 de Ag. de 2018
Editada: Dimitris Kalogiros el 25 de Ag. de 2018
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

Categorías

Más información sobre Polynomials en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by