Plot function given by integral depending on a parameter

I have a function given as an integral depending on a parameter, say
.
(Please ignore the fact that this can be integrated exactly.) Here I'm thinking of a as a parameter that can take any real value. Given a fixed value for a, I'd like to plot the function of x given by
.
Here's my best attempt:
f = @(a,t) sin(a.*t); % Define integrand
F_scalar = @(a,x) integral(@(t) f(a,t), 0, x); % Function of interest, except that x must be a scalar here
F = @(a,x) arrayfun(F_scalar, a, x); % Vectorized version of function of interest
fplot(@(x) F(1,x))
This gives me a plot, but with the following warning: "Warning: Function behaves unexpectedly on array inputs. To improve performance, properly vectorize your function to return an output with the same size and shape as the input arguments."
The problem seems to be that arrayfun should accept arguments with the same dimensions, whereas in the last line of code I'm setting but letting MATLAB pass a vector for x. Any ideas?

 Réponse acceptée

Torsten
Torsten le 11 Avr 2022
Modifié(e) : Torsten le 11 Avr 2022
f = @(a,t) sin(a*t);
F = @(a,x) integral(@(t)f(a,t),0,x);
a = 1;
x = 0:0.1:2*pi;
Result = arrayfun(@(x)F(a,x),x);
plot(x,Result)

3 commentaires

Note:
If your integral is expensive, then you can improve efficiency by dividing the range into segments
F = @(a,low,high) integral(@(t)f(a,t),low,high);
partial_results = arrayfun(@(low,high)F(a,x), x(1:end-1), x(2:end));
initial_value = F(a,0,x(1));
Result = cumsum([initial_value, partial_results]);
This integrates between adjacent x values, instead of integrating from 0 to x each time.
Torsten
Torsten le 12 Avr 2022
Modifié(e) : Torsten le 12 Avr 2022
To summarize:
a = 1;
x = 0:0.1:2*pi;
f = @(a,t) sin(a*t);
F = @(a,low,high) integral(@(t)f(a,t),low,high);
partial_results = arrayfun(@(low,high)F(a,low,high), x(1:end-1), x(2:end));
initial_value = F(a,0,x(1));
Result = cumsum([initial_value, partial_results]);
plot(x,Result)
Thank you, this works!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

Produits

Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by