Effacer les filtres
Effacer les filtres

symbolic function as input to a matlab function

23 vues (au cours des 30 derniers jours)
Francesco Pio
Francesco Pio le 19 Juil 2023
Commenté : VBBV le 22 Juil 2023
Hello everyone.
Let's suppose I have a symbolic function like this :
syms f(x)
f(x) = exp(x + 5);
I have to pass this symbolic function as an argument to a matlab function. Is this syntax correct?
function number = example(f)
arguments (Input)
f (1,1) sym
end
number = double(solve(f(x) == 5));
when i call the function, what is the correct syntax?
number = example(f)
or
number = example(f(x))
Also, the body of the function is wrong and it works only if i add "syms x" to it. Is this syntax correct or should I do it another way?
function number = example(f)
arguments (Input)
f (1,1) sym
end
sym x
number = double(solve(f(x) == 5));

Réponse acceptée

Nandini
Nandini le 19 Juil 2023
The syntax you provided for passing a symbolic function as an argument to a MATLAB function is almost correct. However, there are a few modifications needed to make it work correctly.
First, when defining the symbolic function `f(x)`, you need to use the `sym` function to declare `x` as a symbolic variable. Here's the corrected code for defining the symbolic function:
syms f(x)
syms x
f(x) = exp(x + 5);
Next, when calling the `example` function, you need to pass the symbolic function `f` without explicitly specifying the variable `x`. The correct syntax would be:
number = example(f);
Now, let's correct the body of the `example` function. You can declare `x` as a symbolic variable within the function, and then use it in the `solve` function. Here's the corrected code:
function number = example(f)
arguments (Input)
f (1,1) sym
end
sym x
number = double(solve(f(x) == 5, x));
end
With this corrected code, you can call the `example` function as `number = example(f);`, and it will correctly solve the equation `f(x) == 5` using the symbolic function `f` and return the solution as a double value in the variable `number`.
Hope it helps you.
  2 commentaires
Francesco Pio
Francesco Pio le 20 Juil 2023
thanks a lot, it really helps!
VBBV
VBBV le 22 Juil 2023
Hi @Francesco Pio. another way to call the function is by using two input arguments to the function example as shown below.
syms f(x) x % define x as symbolic variable
f(x) = exp(x + 5);
number = example(f,x) % pass it as input argument to the function
number = -3.3906
function number = example(f,x)
number = double(solve(f(x) == 5));
end

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by