How can I fix this trapezium rule script?

1 Ansicht (letzte 30 Tage)
Callum C
Callum C am 6 Feb. 2016
Bearbeitet: John D'Errico am 6 Feb. 2016
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.

Antworten (1)

John D'Errico
John D'Errico am 6 Feb. 2016
Bearbeitet: John D'Errico am 6 Feb. 2016
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.

Community Treasure Hunt

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

Start Hunting!

Translated by