Can't integrate function using Matlab
Show older comments
I am trying to do a basic integration of a formula for 4 different values. After doing a bit of reading, apparently I need to create a function handle but I am not getting any success. I have put my attempt below. I might be missing more though.
L=0:100;
L_bar=25;
sigma_d =[0.25, 0.5, 0.75, 1.0];
mu = log(L_bar) - 0.5*(sigma_d).^2;
L_tilda = exp(mu);
% eta_r = P.*exp(-r./L);
% I want to integrate eta from zero to infinity where P has changing
% variables to give 4 different plots.
r = 0:100;
% I was just testing below to see if a loop would run before attempting to
% plot anything
P = zeros(1,length(L));
fun = @(r) P.*exp(-r./L);
for ii=1:numel(sigma_d)
P= 1./(L.*sqrt(2*pi)*sigma_d(ii)).*exp(-log(L/L_tilda(ii)).^2/(2*sigma_d(ii)^2)) ;
eta_r = integral(fun,0,inf);
end
Accepted Answer
More Answers (1)
You will have to explicitly change the function handle to change its definition
P=pi;
fun = @(x) P*x;
P=3;
%fun(3) is not equal to 3*3=9
fun(3)
L=0:100;
L_bar=25;
sigma_d =[0.25, 0.5, 0.75, 1.0];
mu = log(L_bar) - 0.5*(sigma_d).^2;
L_tilda = exp(mu);
% eta_r = P.*exp(-r./L);
% I want to integrate eta from zero to infinity where P has changing
% variables to give 4 different plots.
r = 0:100;
% I was just testing below to see if a loop would run before attempting to
% plot anything
for ii=1:numel(sigma_d)
P= 1./(L.*sqrt(2*pi)*sigma_d(ii)).*exp(-log(L/L_tilda(ii)).^2/(2*sigma_d(ii)^2));
fun = @(x) P.*exp(-x./L);
eta_r=integral(fun,0,Inf,'ArrayValued',true)
end
Since you are dividing by 0 (first element of L), you get a NaN and thus the warning from the integral() solver.
3 Comments
David Harra
on 9 Feb 2023
Dyuman Joshi
on 9 Feb 2023
"I need to be integrating with respect to L"
You should have mentioned that before. By the definition of the function handle, I took it as you are integrating w.r.t r
Now as you want to integrate w.r.t L, is there a need to define L=0:100?
Or L is a variable in the definition of P as well?
David Harra
on 9 Feb 2023
Categories
Find more on MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


