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

2 views (last 30 days)
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.

Accepted Answer

Torsten
Torsten on 2 Oct 2022
Edited: Torsten on 2 Oct 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 Comments
Sean Flanagan
Sean Flanagan on 2 Oct 2022
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 on 2 Oct 2022
So now you also have a solution with a for loop :-)

Sign in to comment.

More Answers (1)

Walter Roberson
Walter Roberson on 2 Oct 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

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!