フィルターのクリア

Simpson's rule implementation

4 ビュー (過去 30 日間)
Adomas Bazinys
Adomas Bazinys 2018 年 5 月 6 日
編集済み: Jan 2018 年 5 月 7 日
function I = simpsons()
f=@(x) (3+x.^1/2);
a = 1;
b = 6;
n = 20;
disp('n I h')
disp('________________________________')
while (n <= 140)
if numel(f)>1 % If the input provided is a vector
n=numel(f)-1;
h=(b-a)/n;
I = h/3*(f(1)+2*sum(f(3:2:end-2))+4*sum(f(2:2:end))+f(end));
else % If the input provided is an anonymous function
h=(b-a)/n;
xi=a:h:b;
I = h/3*(f(xi(1))+2*sum(f(xi(3:2:end-2)))+4*sum(f(xi(2:2:end)))+f(xi(end)));
end
fprintf('%f \t %f \t %f \n', n, I, h);
n=n+20;
end
end
Hey, I'm trying to implement Simpson's rule in matlab. I want to make n every loop n=n+20 and get different I values, but I do not get it. Where is the problem? I is numerical integration formula.

回答 (1 件)

Jan
Jan 2018 年 5 月 7 日
編集済み: Jan 2018 年 5 月 7 日
The number of steps does not matter, if the function is linear:
f=@(x) (3+x.^1/2)
x.^1/2 is (x .^ 1) / 2, which is the same as x/2. Operator precedence: power is higher than division. I guess you mean:
f = @(x) (3 + x.^(1/2))
% or: f=@(x) (3 + x.^0.5)
% or: f=@(x) (3 + sqrt(x)) % Fastest

カテゴリ

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

製品

Community Treasure Hunt

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

Start Hunting!

Translated by