How can I fix this trapezium rule script?

1 次查看(过去 30 天)
Hi, sorry if this is a stupid question, but I'm fairly new to MATLAB. I'm trying to loop the trapezium rule over multiple values of n, so that I can produce a table of how the calculated area varies with the number of strips. Currently this is what I've tried:
a=input('value of a: ');
b=input('value of b: ');
for n=4:2:20
answer=trap(a,b,n);
end
truth=log(b)-log(a);
disp([n,answer,truth])
This only yields me one line in the table though, for n=2. I'm not sure what I'm doing wrong here.
Thanks in advance.

回答(1 个)

John D'Errico
John D'Errico 2016-2-6
编辑:John D'Errico 2016-2-6
Your computation of answer and the display are outside of the loop.
Just move them inside. Since "truth" does not change, but is used inside the loop, move it to the beginning.
a=input('value of a: ');
b=input('value of b: ');
truth=log(b)-log(a);
for n=4:2:20
answer=trap(a,b,n);
disp([n,answer,truth])
end
Alternatively, you could have generated the answer as an array, then displaying the entire set of results at the end.

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by