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

2 ビュー (過去 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 Center および File ExchangeLoops 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