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

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 comentario

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.

Iniciar sesión para comentar.

Respuestas (1)

Azzi Abdelmalek
Azzi Abdelmalek el 17 de Jul. de 2015
Editada: Azzi Abdelmalek el 17 de Jul. de 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

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Preguntada:

el 17 de Jul. de 2015

Comentada:

el 17 de Jul. de 2015

Community Treasure Hunt

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

Start Hunting!

Translated by