Trapezium Rule example won't work?

8 ビュー (過去 30 日間)
Issie
Issie 2019 年 3 月 4 日
編集済み: Issie 2019 年 3 月 7 日
I do not understand why this code is not working? I am trying to estimate the integral of e^-x2 between x=0 and x=2 using the trapezium rule

採用された回答

Steven Lord
Steven Lord 2019 年 3 月 4 日
You're combining a function declaration and a function call.
Call your function something other than trapz because that's already a function in MATLAB. Let's call it IssieTrapz. It takes four input arguments, which I suspect your function accepts in the following order:
function I = IssieTrapz(f, a, b, n)
This is line 1 of your function. It replaces your original line 1. That's the declaration of the IssieTrapz function.
Now when you call IssieTrapz, that's when you specify the function and give values for a, b, and n.
result = IssieTrapz(@(x) exp(-x^2), 0, 2, 10);
  2 件のコメント
Issie
Issie 2019 年 3 月 4 日
Okay, I have replaced line 1 with what you suggested.
But I am still unsure as to what you mean by the second bit and where I would put this in my code? Do you not have to define what f is?
Steven Lord
Steven Lord 2019 年 3 月 4 日
That second line doesn't go inside your function. That's how you call (use) your function. Type it in the Command Window. When you call your function like that, whatever you pass in as the first input argument will be assigned the name f inside your function. So for this call, f is @(x) exp(-x^2).
You could call it a second time with a different function to change what f is. If you called it like this:
result2 = IssieTrapz(@cos, -pi, 2*pi, 42)
f would be @cos for that call to IssieTrapz.
See this documentation page for a brief introduction to calling functions.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeFunctions についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by