How to display value of particular iteration in a loop
Mostrar comentarios más antiguos
I am having a slight problem, I'd like to find a relative error without knowing the analytical solution. I have an equation where i need to find the value of F using composite mid rule when the relative error is less than 1%. Here is my code so far: The equation is F= integral (from 0 to 30) of (200*(z(n)/(5+z(n)))*exp((-2*z(n))/30))dz :
clc
clear all
a=0;
b=30;
s=1000;
dx=(b-a)/s;
z=zeros(1,s);
for n=1:s
z(n)=a+dx/2+(n-1)*dx;
F=0;
for n=1:s
F=F+dx*(200*(z(n)/(5+z(n)))*exp((-2*z(n))/30));
end
sprintf('%6.2f',F)
6 comentarios
Jan
el 14 de Ag. de 2018
You forgot to ask a question. What is the problem with this code?
Piotr Haciuk
el 14 de Ag. de 2018
Piotr Haciuk
el 14 de Ag. de 2018
Piotr Haciuk
el 14 de Ag. de 2018
Piotr Haciuk
el 14 de Ag. de 2018
Respuestas (1)
Alberto Mora
el 14 de Ag. de 2018
Maybe you can use this piece of code inside the for loop:
if n==desired_iteration
disp('This is the desired iteration!');
disp(['The result at ',num2str(n),' iteration is ',num2str(result)]);
end
6 comentarios
Piotr Haciuk
el 14 de Ag. de 2018
Alberto Mora
el 14 de Ag. de 2018
if true
% code
endclc
clear all
a=0;
b=30;
s=1000;
dx=(b-a)/s;
z=zeros(1,s);
for n=1:s
z(n)=a+dx/2+(n-1)*dx;
F=0;
for n=1:s
F=F+dx*(200*(z(n)/(5+z(n)))*exp((-2*z(n))/30));
if n==desired_iteration
disp('This is the desired iteration!');
disp(['The result at ',num2str(n),' iteration is ',num2str(result)]);
end
end
end
sprintf('%6.2f',F)
Obviously you need to use your variable instead of "desired_iteration", "result".
Piotr Haciuk
el 14 de Ag. de 2018
Torsten
el 14 de Ag. de 2018
Choose n such that
K*(b-a)^3/(24*n^2) < 0.01
where
K = max_[x in [a;b]] |f''(x)|
Best wishes
Torsten.
Piotr Haciuk
el 14 de Ag. de 2018
Torsten
el 14 de Ag. de 2018
As you can see from the answer provided in your textbook, the authors seem to define the relative error as
|F_(2*n)-F_n|/|F_n|
So simply calculate F for n and 2*n and evaluate the expression above. If it is less than 0.01, you are done. Otherwise you will have to increase n and repeat the procedure.
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!