symbolic function as input to a matlab function
38 views (last 30 days)
Show older comments
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));
0 Comments
Accepted Answer
Nandini
on 19 Jul 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 Comments
VBBV
on 22 Jul 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
function number = example(f,x)
number = double(solve(f(x) == 5));
end
More Answers (0)
See Also
Categories
Find more on Symbolic Math Toolbox 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!