I am writing a lagrange interpolator function and when runnign the test code, my program fails for most tests and i get "matrix dimensions must agree" error. I am not sure where the error is. Can anybody tell? Also, is it appropriate for me to be using .* as opposed to just * operators? Thanks.
function p = lagrangeval(x,y,w)
%% lagrangeval evalutates the Lagrange interpolant for a set of knots (x,y)
%% Inputs: numbers x1,x2,..xn; values f(x1),f(x2)..f(xn)
%% Output: p - the value of the polynomial going through the n data points
function p = lagrangeval(x,y,w)
%% lagrangeval evalutates the Lagrange interpolant for a set of knots (x,y)
%% Inputs: numbers x1,x2,..xn; values f(x1),f(x2)..f(xn)
%% Output: p - the value of the polynomial going through the n data points
n=size(x,2);
k=size(w,2);
p=zeros(n,k);
for i=1:n
p(i,1)=y(i);
end
for l=1:k
for i=1:n-1
for j=1:i
p(i+1,j+1)=(((w(l)-x(i-j+1)).*p(i+1,j))-((w(l)-x(i+1)).*p(i,j)))./(x(i+1)-x(i-j+1));
end
end
end

댓글 수: 3

Walter Roberson
Walter Roberson 2019년 11월 4일
The only issue I find in testing is that you assume that y has at least as many elements as x has columns.
Could you give specific test values that fail for you?
Amanda McGovern
Amanda McGovern 2019년 11월 4일
x = 0:2*pi/5:2*pi; y = sin(x); w = [3 4]
x = 0:2*pi/8:2*pi; y = sin(x); w = [3 4 5];
Walter Roberson
Walter Roberson 2019년 11월 5일
I do not encounter any error messages when I pass the above values to your function.

댓글을 달려면 로그인하십시오.

답변 (1개)

David Hill
David Hill 2019년 11월 4일

0 개 추천

Length of x and y must be equal since they are points. The following functions evaluations lagrange polynomial at each value of w (any length).
function p = lagrangeval(x,y,w)
a=length(x);
b=ones(1,a-1);
p=zeros(1,length(w));
for i=1:a
p=p+arrayfun(@(z)y(i)*(prod(z*b-x(x~=x(i)))/prod(x(i)*b-x(x~=x(i)))),w);
end
end

카테고리

도움말 센터File Exchange에서 Polynomials에 대해 자세히 알아보기

제품

릴리스

R2019a

질문:

2019년 11월 4일

댓글:

2019년 11월 5일

Community Treasure Hunt

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

Start Hunting!

Translated by