Simple solution to a simple problem

1 回表示 (過去 30 日間)
Chris
Chris 2013 年 6 月 14 日
Hey, Im trying to write an algorithm to compute the integral of a user inputted function with limits. I wrote the following code:
function I=Simpson38(Fun,a,b)
N=3;
dif=1;
I1=0;
func=inline(Fun);
while dif>0.001
h=(b-a)/N;
Ia=(h*3/9)*(func(1)+func(N+1));
Ib=(h*3/9)*(2*sum(func(4:3:(N-2))));
Ic=(h*3/9)*(3*sum(func(2:3:(N-1)))+sum(fun(3:3:N-1)));
I2=Ia+Ib+Ic;
dif=(I1-I2)/I2;
I1=I2;
N=N*2;
end
I=I1;
When i run the code i get the following error: ??? Error using ==> inlineeval at 15 Error in inline expression ==> 1/(1+9*x.^2) Matrix dimensions must agree.
Error in ==> inline.subsref at 27 INLINE_OUT_ = inlineeval(INLINE_INPUTS_, INLINE_OBJ_.inputExpr, INLINE_OBJ_.expr);
Error in ==> Simpson38 at 9 Ib=(h*3/9)*(2*sum(func(4:3:(N-2)))); What could be the problem?

回答 (1 件)

Richard Brown
Richard Brown 2013 年 6 月 14 日
Try
1./(1 + 9*x.^2)
i.e. a '.' before the division
  2 件のコメント
Chris
Chris 2013 年 6 月 14 日
Worked! Thanks!
Richard Brown
Richard Brown 2013 年 6 月 16 日
Great! Please "accept" the answer so people browsing the forum knows it's been answered

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

カテゴリ

Help Center および File ExchangeNumerical Integration and Differentiation についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by