need a for loop that displays value at each point of x.
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Sean Flanagan
am 2 Okt. 2022
Kommentiert: Torsten
am 2 Okt. 2022
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.
0 Kommentare
Akzeptierte Antwort
Torsten
am 2 Okt. 2022
Bearbeitet: Torsten
am 2 Okt. 2022
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 Kommentare
Weitere Antworten (1)
Walter Roberson
am 2 Okt. 2022
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
0 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!