How to write a for loop with break condition... (reimann sum)

2 views (last 30 days)
I am trying to create a for loop for a reimann sum with the condition that it will stop when the percent difference between iterations is <1%. Here is what I have so far...
x=9;
y=17;
L=10;
W=20;
sum=0;
sum2=0;
for n=1:2:inf
p=(((-1)^(n+1)+1)/n)*sin((n*pi*x)/L)*((sinh((n*pi*y/L))/(sinh((n*pi*W/L)))));
p2=(((-1)^(n+2)+1)/(n+1))*sin((n+1)*pi*x/L)*((sinh((n+1)*pi*y/L)/(sinh((n+1)*pi*W/L))));
sum=sum+p;
sum2=sum2+p2;
if ((sum2-sum)/sum) < .01
break
else
continue
end
end
sum*(2/pi)
  1 Comment
Walter Roberson
Walter Roberson on 17 Jul 2015
Please do not name a variable "sum". "sum" is an important MATLAB routine to do addition, and you are quite likely to run into problems with confusing that routine with the variable. If not you then whoever reads your code is going to get confused.

Sign in to comment.

Answers (1)

Azzi Abdelmalek
Azzi Abdelmalek on 17 Jul 2015
Edited: Azzi Abdelmalek on 17 Jul 2015
Use while loop
sum=0;
sum2=0;
s1=1;
while s1>=0.01
p=(((-1)^(n+1)+1)/n)*sin((n*pi*x)/L)*((sinh((n*pi*y/L))/(sinh((n*pi*W/L)))));
p2=(((-1)^(n+2)+1)/(n+1))*sin((n+1)*pi*x/L)*((sinh((n+1)*pi*y/L)/(sinh((n+1)*pi*W/L))));
sum=sum+p;
sum2=sum2+p2;
s1=(sum2-sum)/sum;
end

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!