Turning my function into an infinite loop

2 ビュー (過去 30 日間)
Faris Sulam
Faris Sulam 2021 年 1 月 4 日
コメント済み: Faris Sulam 2021 年 1 月 4 日
Hi guys,
I wanted to ask of you about this code. I made a Simpson's rule code that does work when i place in the variables but now i want to edit it so that instead of placing iterations as a variable, the function would continuously iterate until it reaches a certain accpetable error.
function [ s ] = Simpson13( f,a,b,M)
h=(b-a)/(2*M);
s1=0;
s2=0;
for k=1:M;
x=a+h*(2*k-1);
s1=s1+f(x);
end
for k=1:(M-1);
x=a+h*2*k;
s2=s2+f(x);
end
s=h*(f(a)+f(b)+4*s1+2*s2)/3;
disp(s)
end
My plan is to replace all of the M into 'inf' and then putting an error statement afterwards to stop the infinite loop
TolMax=0.01; %the acceptable error
TolCur= abs(s(k)-s(k-1))/(s(k)); %I assume this is how one would calculate the error of the current value with the previous
if TolCur < TolMax
break
end
But according to matlab, i cant do this. Can someone give me any pointers to do this?

採用された回答

Mischa Kim
Mischa Kim 2021 年 1 月 4 日
編集済み: Mischa Kim 2021 年 1 月 4 日
Hi Faris, instead of a for loop use a while loop with a condition like
while abs(s_k - s_k1) > TolMax
% here comes your code
end
Above the loop you need to assign values to s_k and s_k1 so that you enter the loop.
  3 件のコメント
Mischa Kim
Mischa Kim 2021 年 1 月 4 日
My assumption was that your idea was to decrease the step size (by increasing M) until a certain accuracy is achieved. In this case you could simply do something like the below. The while loop continuously calls your function until TolMax is reached.
f = @(x) cos(x); % this is just an example equation
a = 0;
b = pi/2;
M = 10;
TolMax = 1e-10;
while (Simpson13(f,a,b,M)-Simpson13(f,a,b,M+1)) > TolMax
M = M + 1;
end
fprintf('Integral = %10.6e with tol = %10.6e reached with %d steps\n',...
Simpson13(f,a,b,M),TolMax,M);
Faris Sulam
Faris Sulam 2021 年 1 月 4 日
Ah ok, your idea is way better, thanks

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

その他の回答 (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