hey can any one help me with this error?

% Clear workspace & window
clear; clc;
% Create a vector for x values
x = [0, 1, 2, 3, 4, 5, 6, 7];
% Create a vector for y values
y = [0.5, -2, 3, 4, -1, 7, 5, 2];
% Set the value at which interpolated value has to be found
xp = 2.5;
% Call function to find the interpolated value at xp = 2.5
yp = Lagrange_IP(x, y, xp);
% Print the interpolated value
fprintf('The interpolated value at x = %.1f is %.6f\n', xp, yp);
% Create a vector for more x values
xp = linspace(x(1), x(end));
% Create a vector to store the interpolated values for each x values
yp = zeros(1, length(xp));
% Loop for each x values in vector
for i = 1 : length(xp)
% Call function to find the ith interpolated value
yp(i) = Lagrange_IP(x, y, xp(i));
end
% Plot the original values & interpolated values
plot(x, y, 'ro', xp, yp);
% Set x-axis label
xlabel('x');
% Set y-axis label
ylabel('y');
% Set title
title('Lagrange Interpolation');
% Function used to find the interpolated value using Lagrange Interpolation
function yp = Lagrange_IP(x, y, xp)
% Set the intial value of interpolated value
yp = 0;
% Loop for each value of x vector
for i = 1 : length(x)
% Used to find the interpolated value
p = 1;
% Loop for each value of x vector
for j = 1 : length(x)
% If the i and j both ae not equal means not same point
if i ~= j
% Compute the interpolated value for i & j
p = p * (xp - x(j))/(x(i) - x(j));
end
end
% Compute the interpolated value for ith value of y
yp = yp + p * y(i);
end
end

5 Commenti

For me, your code works fine.
What error message do you get ?
What error are you getting?
I can run this in R2019b and R2009b without error.
If you're trying to run this as a script with a local function in an older version, you'll have to put the function into its own file. Scripts cannot have local functions in older versions.
Otherwise, I can only guess what error you got.
When you get an error, show the error message. The COMPLETE error mesage. So everything in red. Otherwise, people need to guess what you did or what is the problem. And in this case, it appears that you have working code, since @Torsten says it works. So you are doing something that is a problem, but we cannot guess what that may be without you telling the error message you get.

Accedi per commentare.

 Risposta accettata

DGM
DGM il 25 Mag 2022
Modificato: DGM il 25 Mag 2022
Okay, then that's what I suspected. Move the function section into its own file and save it. You can't have the function inside the script if you're running a version older than R2016b.
See the attached files.

Più risposte (0)

Prodotti

Release

R2007b

Richiesto:

il 25 Mag 2022

Modificato:

DGM
il 25 Mag 2022

Community Treasure Hunt

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

Start Hunting!

Translated by