How to integrated a function when I know its value at specific points
조회 수: 7 (최근 30일)
이전 댓글 표시
Dear all,
In a vector B of 10 000 lines I have the value of a function B at specific points (x,y). I have a vector x and a vector y such as B(i) equals the value of the function at the point (x(i),y(i)) which means that Vector_B(i)=Function_B(x(i),y(i)). x and y vectors are not sorted in a specific way and I need to integrate B over x and y. I think I need to use cumtrapz or trapz but I don't know how to do it.
Thank you for your help !
댓글 수: 1
답변 (3개)
Vishnu
2023년 6월 26일
Hi BOnjour,
To solve the integral we need to sort the points in the ascending order.
The sorted indices are obtained using
[sorted_x, sorted_indices] = sort(x)
[sorted_y, sorted_indices] = sort(y)
we use the 'trapz' function to calculate the integral of B with respect to x and y. The resulting integrals are stored in integral_wrt_x and integral_wrt_y, respectively.
Here is the sample code how you can do
[sorted_x, sorted_indices] = sort(x);
sorted_y = y(sorted_indices);
sorted_B = B(sorted_indices);
integral_wrt_x = trapz(sorted_x, sorted_B);
[sorted_y, sorted_indices] = sort(y);
sorted_x = x(sorted_indices);
sorted_B = B(sorted_indices);
integral_wrt_y = trapz(sorted_y, sorted_B);
disp(integral_wrt_x);
disp(integral_wrt_y);
John D'Errico
2023년 6월 29일
Are these scattered points? If so, then what do you mean to integrate over a rather non-convex domain? For example, I'll pick 100 scattered points.
x = rand(100,1);y = rand(100,1);
% just to pick a simple function where I can compute an integral
% analytically, IF I wanted to do so, AND I knew the domain of that
% integral.
z = x.^2 + y.^2;
plot3(x,y,z,'o')
So we have a nice simple function. However, it is not so clear as to what you intend as an "integral" in the case of such scattered data, as I have shown.
plot(x,y,'o')
As you can see, x and y do not really fill the unit square on which they are defined. So we cannot integently compute an integral over the entire unit square.
Can I compute an integral? Well, yes. I might decide to compute the integral of the function over the convex hull of the data in x and y. That is relatively easy. But that would not go at all into the corners of that unit square.
Or, I might decide to extrapolate that surface over the entire domain, implicitly fitting it, and then integrate that extrapolated result. Of course, that would only be as good as my ability to extrapolate.
Finally, it is possible that you actually have a gridded set of points. 10000 points might just represent a 100x100 grid of points. If so, then it is utterly trivial to solve, and you can indeed use trapz. We don't know, and you have not told us enough information to know.
The point is, you need to first explain what you have, more clearly. AND what you think the domain of that inteegral SHOULD be.
댓글 수: 0
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!