フィルターのクリア

Help with loops calculating value

1 回表示 (過去 30 日間)
amateurintraining
amateurintraining 2017 年 11 月 20 日
回答済み: Walter Roberson 2017 年 11 月 20 日
I have a function:
function [ I, h ] = Simpson( f, a, b, tol )
n=2;
h=(b-a)/n;
x=h/3;
I=x*(f(a)+4*f((a+b)/2)+f(b));
Iold=I;
n=2*n;
if abs((I-Iold)/Iold)>=tol
n=2*n;
h=(b-a)/n;
for j=1:n/2-1
term1=2*f(2*xj);
xj=a+j*h;
end
for i=1:n/2
term2=4*f(2*xj-1);
xj=a+j*h;
end
x=h/3;
I=x*(f(a)+term1+term2+f(b));
n=n*2;
end
However, I want the function to loop to keep calculating I until
abs((I-Iold)/Iold) is less than the input tol.
How do I do this? Presently, it only calculates when n=2.
  1 件のコメント
Walter Roberson
Walter Roberson 2017 年 11 月 20 日
Why do you have
n=2*n;
twice in your loop? And just before you loop you also have it. Considering the lack of comments, it looks like you are doing too many of those changes to n.

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

回答 (2 件)

KL
KL 2017 年 11 月 20 日
編集済み: KL 2017 年 11 月 20 日
I don't clearly understand what you're trying to do but it looks like you may want to use a while loop,
while abs((I-Iold)/Iold)>=tol
%here goes the part to be repeated until the above condition fails
end
additionally, I have noticed few other things, when you say
for j=1:n/2-1
term1=2*f(2*xj);
xj=a+j*h;
end
for i=1:n/2
term2=4*f(2*xj-1);
xj=a+j*h;
end
  1. You haven't defined xj previously so it's gonna throw you an error.
  2. you're simply repeating the task until you calculate a final value, then why not directly calculate the final value?
j=floor(n/2);
xj = a+j*h;
term1 = 2*f(2*xj);
and similarly the other loop content.

Walter Roberson
Walter Roberson 2017 年 11 月 20 日
You have
for j=1:n/2-1
term1=2*f(2*xj);
xj=a+j*h;
end
every iteration of j, that is going to overwrite all of term1 and xj. There is no point in calculating values that are just going to be overwritten.
Perhaps you should be recording all of the terms and totaling them ?

カテゴリ

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