how to integrate a product with function handle

7 views (last 30 days)
I want to perform a numerical integration with function handle. Please find details below
Nz = 256;
L = 1;
dz = L/Nz;
zgrid = dz*(0:Nz-1)'-L/2;
gN = 20000;
U0 = 5*gN;
U1=1.9*gN;
sigma = 5*dz;
xb = L/4;
tau = 0.01;
h=0.2*gN;
n0=mean(dens(abs(zgrid)<L/10,:));
wp=2*pi*sqrt(gN*n0);
Ub = @(t) U1*(t<tau)+(t>=tau)*(U1+h*sin(wp*(t-tau)));
Vext = @(t) (U0*exp(-(zgrid+xb).^2/sigma^2)+Ub(t)*exp(-(zgrid-xb).^2/sigma^2));
Now I want to integrate
integrate (Vext *A, zgrid)
where A is a double array matrix of dimension (zgrid,t)
The problem is Vext is function handle and A is numerical values of the dimension (zgrid,t). please help how to do this integration?

Answers (1)

Steven Lord
Steven Lord on 7 May 2021
You can't calculate the product of a number and a function handle. What you can do instead is calculate the product of a number and the result of evaluating that function handle.
fh = @(x) x.^2;
This works and returns a number. It evaluates the function handle with x = 5 then multiplies that result by 2.
y1 = 2*fh(5)
y1 = 50
This works and returns another function handle that you can evaluate. Note that inside the function handle fh2 I evaluate fh at the value that was passed into fh2.
fh2 = @(x) 2*fh(x)
fh2 = function_handle with value:
@(x)2*fh(x)
y2 = fh2(7) % Essentially the same as y1 (except with x = 7 instead of x = 5.)
y2 = 98
This does not work which is why I put it last.
y3 = 2*fh
Operator '*' is not supported for operands of type 'function_handle'.
  1 Comment
Abhik Saha
Abhik Saha on 8 May 2021
Edited: Abhik Saha on 8 May 2021
I understand your point of view. Then one of the possible gateway is to generate the dataset of Vext with dimension zgrid and t. I mean to say Vext(zgrid,t). I am new to matlab so I don't know how to do this can you please tell me how to generate this dataset where lets say zgrid is already defined and t=linspace(0,10,1000).

Sign in to comment.

Categories

Find more on Shifting and Sorting Matrices 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!