# How to combine 2 function handles of different variables?

25 vues (au cours des 30 derniers jours)
Niklas Kurz le 26 Oct 2022
Réponse apportée : KSSV le 26 Oct 2022
Strangely enough I was not able finding an answere to this sinewy problem:
Given 2 function handles
mu = @(n, dmu, mubar) mubar + n*dmu/4;
f = @(t, mu) cos(2*pi*mu*t);
How do I combine them into one? Obviously (in my disfavor) adding doesn't work:
f = f + mu % Error
Please tell me there is a way around just creating a handle manually. Eventually I want something like this:
f = @(n, dmu, mubar, t) cos(2*pi*(mubar + n*dmu/4)*t);
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Réponse acceptée

Karim le 26 Oct 2022
Modifié(e) : Karim le 26 Oct 2022
You need to add the input parameter in order to evaluate the functions. See below for demonstration using some random inputs.
You can indeed add the results of the function handles if the outputs have the same dimensions.
mu = @(n, dmu, mubar) mubar + n*dmu/4;
f = @(t, mu) cos(2*pi*mu*t);
% assume some values
n_in = rand(1);
dmu_in = rand(1);
mubar_in = rand(1);
t_in = rand(1);
% evaluate f1 = f + mu
f1 = f(t_in, mu(n_in, dmu_in, mubar_in)) + mu(n_in, dmu_in, mubar_in)
f1 = -0.3532
If you want to cobine merge the function handles, you can use the symbolic toolbox:
syms n dmu mubar t
% create symbolic expression for mu
mu = mubar + n*dmu/4
mu =
% create symbolic expression for f (define this after mu, since matlab will
% fill in the equation)
f = cos(2*pi*mu*t)
f =
% convert the symbolic expression into a function handle
f = matlabFunction(f)
f = function_handle with value:
@(dmu,mubar,n,t)cos(t.*pi.*(mubar+(dmu.*n)./4.0).*2.0)
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Plus de réponses (1)

KSSV le 26 Oct 2022
mu = @(n, dmu, mubar) mubar + n*dmu/4;
f = @(t, mu) cos(2*pi*mu*t);
fmu = @(x) f(mu)
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Catégories

En savoir plus sur Symbolic Math Toolbox dans Help Center et File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by