Insert number in polynomial

조회 수: 5 (최근 30일)
Chr Mil
Chr Mil 2020년 1월 17일
편집: VBBV 2023년 7월 25일
So I have the polynomial p with syms x and I want the user to give me a number and calculate the polynomial at that point. The problem is that I cannot declare p as polynomial with vector because I don't know the degree. Here's my code :
clc
clear all;
syms x
x_val=[0 -pi/4 -pi/3 -pi/2 pi pi/6 pi/4 pi/3 pi/2 -pi];
y_val=[0 -sqrt(2)/2 -sqrt(3)/2 -1 0 1/2 sqrt(2)/2 sqrt(3)/2 1 0];
g=input('Give corner in raduis (from [p,-p])');
for i=1:10
ar=1;
par=1;
for j=1:10
if i==j
continue %Αν το i==j τοτε να μην υπολογιστεί τίποτα γιατί ο παρονομαστής θα γίνει 0 και ο αριθμητής δεν περιέχει το (x-x1) στο L1
else
ar=ar*(x-x_val(j));
par=par*(x_val(i)-x_val(j));
end
end
L(i)=ar/par;
end
p=0;
for i=1:10
p=p+(y_val(i)*L(i));
end
f= @(x)p;
disp(f(g))

답변 (2개)

Sergey Kasyanov
Sergey Kasyanov 2020년 1월 17일
Hello,
You need to replace f= @(x)p; by f = symfun(p,x);.

VBBV
VBBV 2023년 7월 25일
편집: VBBV 2023년 7월 25일
You can use symsum function in place of for loop. since polynomial p is function of x, its easier to use symbolic summation for a specific range as shown to obtain the symbolic
clc
clear all;
syms x p
x_val=[0 -pi/4 -pi/3 -pi/2 pi pi/6 pi/4 pi/3 pi/2 -pi];
y_val=[0 -sqrt(2)/2 -sqrt(3)/2 -1 0 1/2 sqrt(2)/2 sqrt(3)/2 1 0];
g=4
g = 4
for i=1:10
ar=1;
par=1;
for j=1:10
if i==j
continue %Αν το i==j τοτε να μην υπολογιστεί τίποτα γιατί ο παρονομαστής θα γίνει 0 και ο αριθμητής δεν περιέχει το (x-x1) στο L1
else
ar=ar*(x-x_val(j));
par=par*(x_val(i)-x_val(j));
end
end
L(i)=ar/par;
end
% use symsum function for polynomial P
P = symsum(y_val.*L,x,1,10)
P = 
f = @(p) p + P
f = function_handle with value:
@(p)p+P
disp(f(g))

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by