im working on octave not sure if it would run in matlab, im trying to do a simple lagrange polynomial that plot the points, the function and the lagrange aproximation, so i did the following,
clear all
clc
function [y] = lagrange(x, x0, y0)
n = size(x0,1);
y = 0;
for i=1:n
p = 1;
for j=1:n
if j == i % avoiding division by 0
continue;
endif;
p *= (x-x0(j)) / (x0(i)-x0(j));
endfor;
y += y0(i) * p;
endfor;
endfunction;
x=[0:0.1:5];
x0=[2;2.75;4];
y0=[1/2;1/2.75;1/4];
y=lagrange(x,x0,y0);
I'm having the following problem, "operator *: nonconformant arguments (op1 is 1x41, op2 is 1x41)" which only appears when using a vector in x, if i try and evaluate for example lagrange(3,x0,y0) in a specific point, the function works correctly and there is no problem with it, the problem is when you use a larger vector for x,
So my question is, is there a way i can modify the function so it will work with a larger vector x, or there is a way i can plot the function without using the larger vector directly in the function?
The line
p *= (x-x0(j)) / (x0(i)-x0(j));
means
p = p * (x-x0(j)) / (x0(i)-x0(j));
This * means matrix multiplication, and one can't multiply two matrices (1, 41) and (1, 41): inner dimensions do not match.
What you need there is elementwise multiplication,
p = p .* (x-x0(j)) / (x0(i)-x0(j));
(See docs for an explanation of the difference).
It could be written as
p .*= (x-x0(j)) / (x0(i)-x0(j));
But I suggest avoiding such contraction; in Matlab/Octave it's not used as much as in some other languages, possibly because placing two operands side by side makes the errors in binary operation choice more apparent.