Integration over discrete data - don't know if trapz works here

22 views (last 30 days)
Hey,
I'm trying to integrate a set of data.
I already done: plot(energy,photonflux), where energy is a set of not equaly spaced values for photon energy, and photonflux is the actual amount of photons.
I tried integrating the equation setting a dE=energy(i+1)-energy(i) where dE will be used to integrate.
Since my dE, change for every value the only way i got was too calculate the actual dE for every set of two points where i build a rectangle of height y.
This method alows me to integrate my set of data points quite well but not as perfectly as i would want. The first value for J should be around 66 or 67. And I'm getting about 61. Can i use trapz on this?
q=elementary electron charge.
I want to integrate the black data points.
for i=1:1:length(energy)-1
area=area+photonflux(i)*dE
end
J=area*q
  6 Comments
Jan
Jan on 15 May 2021
With dE=energy(i+1)-energy(i), dE it is a vector. Then you need:
area = 0;
for i = 1:length(energy)-1
area = area + photonflux(i) * dE(i);
% ^^^
end
Please post the complete error message in all cases. "Second and third argument must either be variables or a variable and a nonnegative integer specifying the number of differentiations." looks strange, because the third argument of TRAPZ can be the dimension only and not the number of differentiations. This looks, lkike you have called aother function. The complete error message should clarify this directly.
Tiago Fernandes
Tiago Fernandes on 15 May 2021
if you calculate dE=energy(i+1)-energy(i), dE is going to be a scallar for every iteration.
Because i calculate dE before area.
The error was:
Error using sym/diff (line 36)
Second and third argument must either be variables or a variable and a nonnegative
integer specifying the number of differentiations.
Error in trapz (line 79)
z = diff(x,1,1).' * (y(1:end-1,:) + y(2:end,:))/2;

Sign in to comment.

Answers (1)

Jan
Jan on 15 May 2021
Edited: Jan on 15 May 2021
Using trapz check input sizes and cares for matrices also. But if x and y are vectors, this can be done manually also. The trapezoid sum uses an easy formula:
A = sum(diff(x) .* (y(1:end-1) + y(2:end)) / 2)
Or:
y = y(:);
A = diff(x(:)).' * (y(1:end-1) + y(2:end)) / 2;

Community Treasure Hunt

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

Start Hunting!