Info

Cette question est clôturée. Rouvrir pour modifier ou répondre.

Can someone convert this to matlab code?

1 vue (au cours des 30 derniers jours)
Kevin Wood
Kevin Wood le 29 Sep 2020
Clôturé : MATLAB Answer Bot le 20 Août 2021
  2 commentaires
James Tursa
James Tursa le 29 Sep 2020
What have you tried so far?
Kevin Wood
Kevin Wood le 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

Réponses (1)

James Tursa
James Tursa le 30 Sep 2020
Modifié(e) : James Tursa le 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

Produits


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by