symbolic function as input to a matlab function

33 ビュー (過去 30 日間)
Francesco Pio
Francesco Pio 2023 年 7 月 19 日
コメント済み: VBBV 2023 年 7 月 22 日
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 件のコメント
Francesco Pio
Francesco Pio 2023 年 7 月 20 日
thanks a lot, it really helps!
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 Center および File ExchangeSymbolic Math Toolbox についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by