필터 지우기
필터 지우기

need a for loop that displays value at each point of x.

조회 수: 1 (최근 30일)
Sean Flanagan
Sean Flanagan 2022년 10월 2일
댓글: Torsten 2022년 10월 2일
I need to write a for loop that performs the same calculation as cumtrapz. I have written this code to solve for the total trapezoid value but I am stuck on how to get it to work for for all the points of x.

채택된 답변

Torsten
Torsten 2022년 10월 2일
편집: Torsten 2022년 10월 2일
But I already gave you the formulae how to code "cumtrapz":
0 = ctrapz(1)
[f(x0)+f(x1)]/2 * (x1-x0) = ctrapz(2)
[f(x0)+f(x1)] / 2 *(x1-x0) + [f(x1)+f(x2)]/2 * (x2-x1) = ctrapz(3),
[f(x0)+f(x1)] / 2 *(x1-x0) + [f(x1)+f(x2)]/2 * (x2-x1) + [f(x2)+f(x3)]/2 * (x3-x2) = ctrapz(4)
...
[f(x0)+f(x1)] / 2 *(x1-x0) + [f(x1)+f(x2)]/2 * (x2-x1) + [f(x2)+f(x3)]/2 * (x3-x2) + ... + [f(x19) + f(x20)]/2 * (x20-x19) = ctrapz(21)
Here they are again with the integration of exp(x) in [0 1] as example:
x = 0:0.1:1;
y = exp(x);
ctrapz = zeros(1,numel(x));
for i = 1:numel(x)-1
ctrapz(i+1) = ctrapz(i) + (y(i)+y(i+1))/2 * (x(i+1)-x(i));
end
hold on
plot(x,y-1)
plot(x,ctrapz)
hold off
  댓글 수: 2
Sean Flanagan
Sean Flanagan 2022년 10월 2일
Cheers Torsten,
I did it with cumtrapz and no for loop, I was just seeing if anyone had any input on how to write a for loop without using cumtrapz.
cumtrapz(Q2x,Q2y)
Gives all the points of x with no need of a for loop.
Torsten
Torsten 2022년 10월 2일
So now you also have a solution with a for loop :-)

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2022년 10월 2일
You are calculating with floating point coefficients in two different ways. You are using == to test equality, which tests for bit-for-bit them being the same value (with the exception that -0 and 0 are treated as equal). Because they are calculated different ways, it is to be expected that they might not give exactly the same answer, that the last couple of bits might be different.
By the way, you can make the logic more compact:
if m == 1 || m == length(Q2y)
TotalTrapVal(m,1) = Q2y(m);
else
stuff
end

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by