Trapezoidal rule in a for loop

7 ビュー (過去 30 日間)
Mathias Pettersen
Mathias Pettersen 2019 年 9 月 23 日
コメント済み: James Tursa 2019 年 9 月 24 日
d
  2 件のコメント
awezmm
awezmm 2019 年 9 月 23 日
Are you getting an error or the values are just not coming out right
James Tursa
James Tursa 2019 年 9 月 24 日
Mathias, it is considered rude to delete your question after it has received answers. This also can render this thread useless to other readers who might be having similar problems.

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

採用された回答

James Tursa
James Tursa 2019 年 9 月 23 日
編集済み: James Tursa 2019 年 9 月 24 日
You made a good start, but there are several problems with your summation. You don't accumulate into your trapez variable, you don't use your index i in your function evaluation, you have your endpoints evaluated multiple times inside your loop, etc.
It would probably be best for you to code the logic up exactly as it appears in the formula. So, first do the summation. Then add the endpoints. Then multiply by (b-a)/n. Also, why not make your life simpler and use the same index variable k that is used in the formula? So, the outline would be this:
trapez = 0; % Initialize your summation to 0
for k = 1: n - 1 % use k as the index so it looks like the formula
trapez = trapez + calculateFormula(_____); % you fill in the value here based on formula
end
trapez = _____ + trapez + _____; % you add in the end points here
trapez = _____ * trapez; % you fill in the multiplying factor here
Try to fill in the blanks above to see if you can get it to work. If you have more problems, come back and ask for more help with the specific problems you are having.
  2 件のコメント
Mathias Pettersen
Mathias Pettersen 2019 年 9 月 24 日
thanks so much. Does this look right?
a = -3;
b = 3;
n = 10;
trapez = 0;
for k = 1: n - 1
trapez = trapez + sum(calculateFormula(a + (k.*(b-a)./n)) + calculateFormula(b)./2);
end
trapez = trapez + calculateFormula(a)/2;
trapez = trapez * ((b-a)/n)
James Tursa
James Tursa 2019 年 9 月 24 日
編集済み: James Tursa 2019 年 9 月 24 日
No, it doesn't. But you are getting closer. You don't need the sum( ) function inside your loop since you are in fact doing the summation manually. Also, the f(b)/2 is one of the endpoints that gets added after the loop (look at your formula closely and you will see that it is not intended to be inside the summation).

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

その他の回答 (0 件)

カテゴリ

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