简体   繁体   中英

Problems attaching a function handle on Matlab to integral expression

I have an integral expression which I defined on Matlab using

x = 0:1/1000:1;
g = @(x) (exp(-1./x.^2).*heaviside(x)).*(exp(-1./(1-x).^2).*heaviside(1-x));
t = 0:1/1000:1; 
f = zeros(size(t));
for i = 1:length(t)
    f(i) = integral(g,0,t(i));
end

I can plot it, for example, using plot(t,f) , but for other purposes I would like to attach a function handle to f , ie something like f = @(t) zeros(size(t)) . I have not been able to figure it out thus far. f = @(t) integral(@(x)g(x),0,t) is also not sufficient.

Sorry, I can't comment yet. But does this work?

funcHand= @(t) integral(g,0,t);

You don't have to define x in your code above, since the input to integral is a function handle.

Then to check it's the same:

f2 = zeros(size(t));
for i = 1:length(t)
    f2(i) = funcHand(t(i));
end

Whoops, the other answer said all the above (just replaced the for loop with arrayfun. I didn't see it while writing the answer.

Edit

If you want to build-in the for loop, try:

funcHand= @(t) arrayfun(@(u) integral(g, 0, u),t);

And test:

plot(funcHand(t))

Try

f = @(u) integral(g, 0, u)

The additional level of indirection in g seems superfluous. Note that I have called the input u . Keep in mind that f will not accept vectors as its inputs. So doing something like f(t) in your current workspace will not create the same array as your for loop is doing. You will have to iterate through the array. The convenience function arrayfun will do this for you:

o = arrayfun(f, t)

It is roughly equivalent to the loop you have now:

o = zeros(size(t));
for i = 1:length(o)
    o(i) = f(t(i));
end

arrayfun can actually be incorporated into your function handle to allow it to process vector arguments:

h = @(t) arrayfun(f, t)

To avoid the proliferation of unnecessary function handles, you can do

f = @(t) arrayfun(@(u) integral(g, 0, u), t)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM