Info

This question is closed. Reopen it to edit or answer.

Can someone convert this to matlab code?

1 view (last 30 days)
Kevin Wood
Kevin Wood on 29 Sep 2020
Closed: MATLAB Answer Bot on 20 Aug 2021
  2 Comments
Kevin Wood
Kevin Wood on 29 Sep 2020
Lag_Poly = 0;
for i = 1:N
for k = 1:N
while k~= i
Lag_Poly = Lag_Poly + prod((p - x(k))/(x(i)-x(k)));
end
end
Lag_Poly = Lag_Poly + y(i) * Lag_Poly;
end

Answers (1)

James Tursa
James Tursa on 30 Sep 2020
Edited: James Tursa on 30 Sep 2020
So, you don't need any loops for this. Just use the automatic array expansion feature. E.g., take a look at what happens with this calculation:
>> n = 5;
>> x = 1:n
x =
1 2 3 4 5
>> p = rand
p =
0.9134
>> M = (p - x)./(x' - x) % using automic array expansion
M =
-Inf 1.0866 1.0433 1.0289 1.0217
-0.0866 -Inf 2.0866 1.5433 1.3622
-0.0433 -1.0866 -Inf 3.0866 2.0433
-0.0289 -0.5433 -2.0866 -Inf 4.0866
-0.0217 -0.3622 -1.0433 -3.0866 -Inf
>> M(1:n+1:end) = 1 % set diagonals to 1 so they don't influence the product
M =
1.0000 1.0866 1.0433 1.0289 1.0217
-0.0866 1.0000 2.0866 1.5433 1.3622
-0.0433 -1.0866 1.0000 3.0866 2.0433
-0.0289 -0.5433 -2.0866 1.0000 4.0866
-0.0217 -0.3622 -1.0433 -3.0866 1.0000
>> prod(M,2)
ans =
1.1917
-0.3800
0.2968
-0.1338
0.0253
Then just take the dot product of this with your y vector.
This should be OK as long as n isn't too large. If n is too large, then you may need to resort to a loop for part of the calculation.

Tags

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!