How can I fix this trapezium rule script?
조회 수: 3 (최근 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.
댓글 수: 0
답변 (1개)
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.
댓글 수: 0
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!