Effacer les filtres
Effacer les filtres

equation as an output

7 vues (au cours des 30 derniers jours)
Clara Vivian
Clara Vivian le 2 Oct 2021
Réponse apportée : Walter Roberson il y a environ 10 heures
can you make an equation as an output of a function?
like, for example I want to make a function that has the output of f =@(x) a*x^2 %a is the number that we input

Réponses (2)

Ayush Modi
Ayush Modi il y a environ 16 heures
Hi Clara,
Yes, you can create a function in MATLAB that returns another function (a function handle to be precise) as its output. Here is the example code to get you started:
a = 10 % Sample input
a = 10
bb = createQuadraticFunction(a) % bb stores the function handle
bb = function_handle with value:
@(x)a*x.^2
bb(10) % Checking the use of function handle
ans = 1000
function f = createQuadraticFunction(a)
% This function returns a quadratic function f(x) = a*x^2
f = @(x) a * x.^2;
end
Refer to the following MathWorks documentation for more information on function handles:

Walter Roberson
Walter Roberson il y a environ 10 heures
syms a x
expr = a*x^2
expr = 
try
f = matlabFunction(expr, 'vars', x)
catch ME
warning(ME.message)
end
Warning: Free variable 'a' must be included in 'Vars' value.
So you have the problem that a is needed but it is not input to the function.
On the other hand,
a = 9.8;
expr = a*x^2
expr = 
f = matlabFunction(expr, 'vars', x)
f = function_handle with value:
@(x)x.^2.*(4.9e+1./5.0)
This has the disadvantage that the value of a is expanded in-line
There is no way with the Symbolic Toolbox to generate a function referring to a captured variable by name

Catégories

En savoir plus sur Symbolic Math Toolbox dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by