How to input equations in MATLAB and operate it?

153 vues (au cours des 30 derniers jours)
Raihan Khalil
Raihan Khalil le 1 Jan 2016
Commenté : Walter Roberson le 23 Juin 2022
I'm using MATLAB R2013a. I want to input an equation in Matlab like f(x) = x^2 - 2*x + 3. And I want it to be inputted by the user. I use inline() function for this. eg.
func = input('Enter a function: ','s');
f = inline(func);
And I have able to do some works with it. But I want to differentiate this equation. I was trying to use diff() function for this. But it doesn't work. When I use diff(f,x); it shows error. How can I solve my problem?

Réponse acceptée

Walter Roberson
Walter Roberson le 1 Jan 2016
You should not use inline(). inline() has been recommended against since MATLAB 5.1, over a decade ago. inline() was replaced with anonymous functions, which can be built using str2func()
You cannot differentiate inline functions or anonymous functions. You can parse the string, and develop a set of routines to differentiate whatever set of input functions you allow. Or you can use the Symbolic Toolbox. For example,
f = sym('x^2 - 2*x + 3')
diff(f,x)
  3 commentaires
Walter Roberson
Walter Roberson le 1 Jan 2016
func = input('Enter a function: ','s');
f = sym(func);
diff(f,x)
Raihan Khalil
Raihan Khalil le 1 Jan 2016
Thank u.

Connectez-vous pour commenter.

Plus de réponses (2)

Jonathan Moussa NDAO
Jonathan Moussa NDAO le 17 Mai 2021
You can try using the matlab builtin func str2func that convert your input in a matlab function handler like syntax('')
func = str2func(input("Enter the function, e.g @(x)2*x - 3: ", "s"));

robert michael
robert michael le 22 Juin 2022
f(x) = x3 – x – 1 input in matlab?

Catégories

En savoir plus sur Function Creation 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