symbolic function as input to a matlab function

36 次查看(过去 30 天)
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));

采纳的回答

Nandini
Nandini 2023-7-19
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 个评论
VBBV
VBBV 2023-7-22
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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Symbolic Math Toolbox 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by