How to integrate a vector-valued function?

I am trying to calculate the attached integral. I have data as vectors r and f(r) tht I load as r and fr, respectively.. The vector x should have the same range as r. Is the following correct? I'm not sure how I should incorporate the fact that f(r) is a function of r, or how the integral depends on x as well.
I try
x = linspace(0.05,17.95,180)';
fun = @(x,r) (r.^2).*(fr-1).*sin(x.*r)./(x.*r);
eq1 = integral(@(r) fun(x,r),0,r(end),'ArrayValued',1);
eq2 = cumtrapz(r,(r.^2).*(fr-1).*sin(x.*r)./(x.*r));
But I get two different answers. Again, r and fr (= f(r)) are both vectors of numbers. Is either eq1 or eq2 one correct? Is neither? I have limited understanding of anonymous functions and numerical integration in MATLAB.

 채택된 답변

Ameer Hamza
Ameer Hamza 2020년 4월 30일

0 개 추천

You need to integrate this function w.r.t. 'r' so you shouldn't use x as a vector in your code. Both of your approaches seem to be doing what you might not intend to do. Check this code, it shows how to do this with integral and trapz. Both will give similar results.
R = linspace(1, 100, 1000); % example r
FR = exp(-R); % example fr
x = linspace(0.05,17.95,180)';
fr = @(r) interp1(R, FR, r, 'pchip');
integrand = @(r,x) r.^2.*(fr(r)-1).*sin(x.*r)./(x.*r);
fx_int = @(x) integral(@(r) integrand(r,x), 0, max(R));
fx_int_v = zeros(size(x));
for i=1:numel(x)
fx_int_v(i) = fx_int(x(i));
end
fx_trapz = @(x) trapz(R, integrand(R, x));
fx_trapz_v = zeros(size(x));
for i=1:numel(x)
fx_trapz_v(i) = fx_trapz(x(i));
end

댓글 수: 4

N/A
N/A 2020년 5월 1일
Thanks, Ameer. One follow-up question: My input 'r' vector is the same as my 'x' vector (which is why I arbitrarily chose the 'x' vector that I did, not sure if that was the correct thing to do or not). Anyway, as a result the following line: 'fr = @(r) interp1(R, FR, r, 'pchip');' doesn't work. What do you suggest I do instead? Thanks again.
Is there an error?
From the image you shared, the 'x' being same length as 'r' should be a coincidence. You can see from the equation that 'r' is the variable of integration, and it is independent of the value of 'x'.
N/A
N/A 2020년 5월 1일
Never mind, it works now. Thank you!
I am glad to be of help.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Numerical Integration and Differentiation에 대해 자세히 알아보기

제품

릴리스

R2018a

질문:

N/A
2020년 4월 30일

댓글:

2020년 5월 1일

Community Treasure Hunt

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

Start Hunting!

Translated by