Integral command doesn't work inside the for loop
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Left Terry
el 6 de En. de 2025
Comentada: Left Terry
el 6 de En. de 2025
Hello. I have this simple code trying to compare analytical solution of few functions with two numerical methods. I used for loop wih the integral command in it but i get many errors.
clear, clc, close all, format long
a = 0;
b = 2;
h1 = b - a;
h2 = (b - a)/2;
n = 1:5;
fprintf('\tAnalytical\tTrapezoid\tSimpson\n\n')
for i = 1:length(n)
f = @(x) x.^n;
I = integral(f,a,b);
Trap = 0.5*h1*(f(a) + f(b));
Simp = (h2/3)*(f(a) + 4*f(h2) + f(b));
fprintf('\t%g\t\t\t\t%g\t\t\t%g\n',I(i),Trap(i),Simp(i))
end
f = @(x) exp(x);
Trap = 0.5*h1*(f(a) + f(b));
Simp = (h2/3)*(f(a) + 4*f(h2) + f(b));
fprintf('\t%g\t\t\t%g\t\t%g\n',I,Trap,Simp)
0 comentarios
Respuesta aceptada
Walter Roberson
el 6 de En. de 2025
Editada: Walter Roberson
el 6 de En. de 2025
a = 0;
b = 2;
h1 = b - a;
h2 = (b - a)/2;
n = 1:5;
fprintf('\tAnalytical\tTrapezoid\tSimpson\n\n')
for i = 1:length(n)
f = @(x) x.^n(i);
I(i) = integral(f,a,b);
Trap(i) = 0.5*h1*(f(a) + f(b));
Simp(i) = (h2/3)*(f(a) + 4*f(h2) + f(b));
fprintf('\t%g\t\t\t\t%g\t\t\t%g\n',I(i),Trap(i),Simp(i))
end
f = @(x) exp(x);
Trap = 0.5*h1*(f(a) + f(b));
Simp = (h2/3)*(f(a) + 4*f(h2) + f(b));
fprintf('\t%g\t\t\t%g\t\t%g\n',I,Trap,Simp)
However, the final printout is nonsense. You are printing out the vector I from the for i loop, along with the scalars Trap and Simp that you just calculated.
1 comentario
Más respuestas (0)
Ver también
Categorías
Más información sobre Stability Analysis en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!