Divided difference(Newton metod)

353 ビュー (過去 30 日間)
Ds31
Ds31 2021 年 10 月 24 日
回答済み: Jan 2021 年 10 月 24 日
I have to calculate divided differences, for vector x and vector y(which is function value of vector x). Divided difference is get when substracting two consecutive y elements, and then dividing that difference with two consecutive x elements. My function has to return vector that consists only of first elements of each divided difference. Here is my code, but not working.(So if we have vector x=[x1, x2, x3, ..., xn] this function has to return vector [f[x1], f[x1,x2],f[x1,x2,x3],...,f[x1,x2,...,xn]].
function div = evalDiv(x,y)
difference = y;
for j=2:length(y)
temp = difference;
for i=j:length(y)
difference(i) = (temp(i)-temp(i-1))/(x(i)-x(i-(j-1));
end
end
div = difference;
end
test = evalDiv([ 1 2 3 4],[5 6 7 8]);
  2 件のコメント
Sargondjani
Sargondjani 2021 年 10 月 24 日
It is not clear what you want to me. You should provide a better formula for what this is supposed to be:
(temp(i)-temp(i-1))/(x(i)-x(i-(j-1));
Also I am not sure you intend to overwrite the values in 'difference'
Ds31
Ds31 2021 年 10 月 24 日
Yes, I'm overwriting it, and on the end with that I will get only first element of each divided difference, that is what I need to return. But not sure why it is not printing anything

サインインしてコメントする。

回答 (1 件)

Jan
Jan 2021 年 10 月 24 日
There was a missing closing parenthesis. The trailing esmivolon suppresses the output. If you omit it, this is displayed:
test = evalDiv([ 1 2 3 4],[5 6 7 8])
test = 1×4
5 1 0 0
function difference = evalDiv(x,y)
difference = y;
for j=2:length(y)
temp = difference;
for i=j:length(y)
difference(i) = (temp(i) - temp(i-1)) / (x(i) - x(i-(j-1)));
% missing: ^
end
end
end

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by