How to store function values generated by a for loop?

7 views (last 30 days)
Good evening everyone.
While trying to assign function values generated by a for loop into a vector, I came up with following error, generated by the code below:
"""
Error using lagrange
Too many output arguments.
Error in ex3 (line 19)
z(i) = lagrange(xx(i),x,y)
"""
I've noticed that code bellow runs perfectly fine without iterating over the vector z, i.e, the output for this code without the vector z just prints out the values of the function,
clc;clear
x = [-2,-1,0,1,2,3];
y = [1,4,11,16,13,-4];
d0 = difdiv(x,y);
d = d0(1,:);
x2 = linspace(-2,2,10);
for i = 1:length(x2)
lagrange(x2(i),x,y)
end
Which outputs,
ans = 11.3474
ans = 1
ans = 1.4554
ans = 3.3594
....and so on for each value in the vector x2.
I'm also using other auxiliary functions for this code, please find them below
function deflatedpolylagrange(x,x_s,d)
n_d = length(d);
n_x = length(x_s);
if n_d ~= n_x
disp('Not possible.')
end
v(1) = d(n_x);
for i = 2:n_x
v(i) = v(i-1) * ( x - x_s(n_x - i + 1) ) + d(n_x - i + 1);
end
v(end)
end
function A = difdiv(x,y)
n = length(x);
A = zeros(n,n);
A(:, 1) = y';
for j=2:n
for i=1:(n - j + 1)
A(i,j) = (A(i + 1, j - 1) - A(i, j - 1)) / (x(i + j - 1) - x(i));
end
end
end
function lagrange(a,x,y)
d_before = difdiv(x,y);
d = d_before(1,:);
deflatedpolylagrange(a,x,d);
end
Is there another way in order to have these values arranged in a vector? I.e, some vector L such that L = [11.3474, 1, 1.4554, 3.3594]
(Pardon me if my coding techniques are not the most correct - I'm just a newbie that just started to learn some things about Matlab in my Numerical Methods class)
Thank you if you read this far!
Below is my current code:
clc;clear
x = [-2,-1,0,1,2,3];
y = [1,4,11,16,13,-4];
d0 = difdiv(x,y);
d = d0(1,:);
xx = linspace(-2,2,10);
z = zeros(1,length(xx));
for i = 1:length(xx)
z(i) = lagrange(xx(i),x,y)
end

Accepted Answer

Kevin Holly
Kevin Holly on 13 Oct 2021
I added outputs to your functions called z.
clc;clear
x = [-2,-1,0,1,2,3];
y = [1,4,11,16,13,-4];
d0 = difdiv(x,y);
d = d0(1,:);
xx = linspace(-2,2,10);
z = zeros(1,length(xx));
for i = 1:length(xx)
z(i) = lagrange(xx(i),x,y);
end
z
z = 1×10
1.0000 1.4554 3.3594 6.1852 9.4060 12.4952 14.9259 16.1715 15.7051 13.0000
function z=lagrange(a,x,y)
d_before = difdiv(x,y);
d = d_before(1,:);
z = deflatedpolylagrange(a,x,d);
end
function z = deflatedpolylagrange(x,x_s,d)
n_d = length(d);
n_x = length(x_s);
if n_d ~= n_x
disp('Not possible.')
end
v(1) = d(n_x);
for i = 2:n_x
v(i) = v(i-1) * ( x - x_s(n_x - i + 1) ) + d(n_x - i + 1);
end
z = v(end);
end
function A = difdiv(x,y)
n = length(x);
A = zeros(n,n);
A(:, 1) = y';
for j=2:n
for i=1:(n - j + 1)
A(i,j) = (A(i + 1, j - 1) - A(i, j - 1)) / (x(i + j - 1) - x(i));
end
end
end

More Answers (0)

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!