Using trapz function to provide answers using loop

Hey,
I am trying to use the trapz function in a loop:
y_approx = zeros ([21 1]);
for i = 1:length(x)
y_approx = trapz(x(i),y)
end
It is providing me the 21 answers but they are incorrect. I think it is using the 21 y for each iteration of x. 21 y values for 1 x value, 21 y values for 2 x values etc. How do I alter the code to make it use the same number of y values as x values?

 采纳的回答

% The way to use trapz
x= 1:20; % x
y = randn(20, 1); % y
ytrapz = trapz(x, y) % integral y dx
ytrapz = -0.0920

4 个评论

I understand how to use trapz, I am trying to calculate an answer for each point of x. Using trapz that way only provides the answer for the whole domain. ie. x =20. I am trying to caculate answers for x=1, x=2, ... x=19, x=20 using a loop.
So this is what you want? You don't need trapz function
x= 1:20; % x
y = randn(20, 1); % y
ytrapz = trapz(x, y) % integral y dx
ytrapz = 0.2045
yloop = zeros(size(x));
for i=2:length(x)
yloop(i) = yloop(i-1) + (y(i) + y(i-1))/2*(x(i)-x(i-1));
end
yloop([1:3 end-3:end])
ans = 1×7
0 -0.7630 -0.5163 -0.4795 -0.0430 0.0183 0.2045
I need the trapz fuction as I am estimating y values using the trapezoidal method. Basically, I need a loop that does:
y2 = trapz(x(1:2),y(1:2))
y3 = trapz(x(1:3),y(1:3))
...
y19 = trapz(x(1:20),y(1:20))
y20 = trapz(x(1:21),y(1:21))
That is not really necessary since the looping code above is doing the trapz job in a more efficient way when you want the intermidiate results.
However, if you insisit, you can do the following (definitely not recommended):
x= 1:20; % x
y = randn(20, 1); % y
ytrapz = trapz(x, y) % integral y dx
ytrapz = 3.5232
yloop = zeros(size(x));
for i=2:length(x)
yloop(i) = yloop(i-1) + (y(i) + y(i-1))/2*(x(i)-x(i-1));
end
yloop([1:3 end-3:end])
ans = 1×7
0 -0.7511 -0.5029 5.0386 4.9629 4.9692 3.5232
% Not recommended:
yloop1 = zeros(size(x));
for i=2:length(x)
yloop1(i) = trapz(x(1:i), y(1:i));
end
yloop1([1:3 end-3:end])
ans = 1×7
0 -0.7511 -0.5029 5.0386 4.9629 4.9692 3.5232

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Numerical Integration and Differentiation 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by