symbolic function as input to a matlab function
조회 수: 38 (최근 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));
댓글 수: 0
채택된 답변
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
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
function number = example(f,x)
number = double(solve(f(x) == 5));
end
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Symbolic Math Toolbox에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!