when I run the code, I only get one plot for f. I need to have a plot for p as well. I need to code this part p(x) =f(x0)l0(x) +f(x1)l1(x) +f(x2)l2(x) to make it works

2 次查看(过去 30 天)
clear all
n = 3; % the order of the polynomial
a = 2.0; % left end of the interval
b = 3.0; % right end of the interval
h = (b - a)/n; % interpolation grid size
t = a:h:b; % interpolation points
f = 1./t; % f(x) = 1./x, This is the function evaluated at interpolation points
%%%% pn(x) = \sum f(t_i)l_i(x)
hh = 0.01; % grid to plot the function both f and p
x = a:hh:b;
l = zeros(n+1, length(x)); %%%% l(1,:): l_0(x), ..., l(n+1): l_n(x)
for i = 1:n+1
j = 1:length(x)
n(i,j) = 1;
d(i,j) = 1;
for k = 1:n+1
if i ~= k
n(i,j) = n(i,j) * (x(j) - t(k));
d(i,j) = d(i,j) * (t(i) - t(k));
end
end
l(i,j) = n(i,j)/d(i,j);
end
sum = 0;
for i=1:n+1
sum = sum + f(i)*L(i,j);
end
plot(t,f,'-b')
hold on
plot(x,sum,'--r' )

采纳的回答

Jogesh Kumar Mukala
Hi,
The lines "n(i,j) = n(i,j) * (x(j) - t(k))" & "d(i,j) = d(i,j) * (t(i) - t(k))" are leading to the error in the code. The number of columns in the first matrix doesnot match with the number of rows in the second matrix which will lead to error in matrix multiplication. There seems to be a for loop missing which you may refer below.
for i = 1:n+1
for j = 1:length(x)
n(i,j) = 1;
d(i,j) = 1;
for k = 1:n+1
if i ~= k
n(i,j) = n(i,j) * (x(j) - t(k));
d(i,j) = d(i,j) * (t(i) - t(k));
end
end
l(i,j) = n(i,j)/d(i,j);
end
end
  2 个评论
ebtisam almehmadi
ebtisam almehmadi 2021-7-13
I have corrected it but I still get on plot for f. I need to have a plot for p as well. I'm not fimiliar with MATLAB, but I think there is somthing wrong with the last for loop.
Jogesh Kumar Mukala
As far as I see your code clearly, You are using same variables at two instances i.e. for order of polynomial(n) and numerator(n(i,j)). This is causing an issue in the final 'for' loop where it is considering 'n' as matrix. Also you could use Element-wise multiplication operator instead of 'for' loop which i mentioned in my above answer. Please refer below code for solving the issues.
clear all
n = 3; % The order of the polynomial
a = 2.0; % Left end of the interval
b = 3.0; % Right end of the interval
h = (b - a)/n; % Interpolation grid size
t = a:h:b; % Interpolation points
f = 1./t; % f(x) = 1./x, This is the function evaluated at interpolation points
hh = 0.01; % Grid to plot the function both f and p
x = a:hh:b;
L = zeros(n+1, length(x));
for i = 1:n+1
j = 1:length(x);
L(i,j) = 1;
d(i,j) = 1;
for k = 1:n+1
if i ~= k
L(i,j) = L(i,j) .* (x(j) - t(k));
d(i,j) = d(i,j) .* (t(i) - t(k));
end
end
L(i,j) = L(i,j)/d(i,j);
end
sum = 0;
for i=1:n+1
sum = sum + f(i)*L(i,j);
end
plot(t,f,'-b')
hold on
plot(x,sum,'--r' )

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Lifting 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by