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

1 次查看(过去 30 天)
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.

请先登录,再进行评论。

更多回答(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