manish.pathak906 asked . 27/01/2020

How can I assign an equation to a variable in MATLAB?

How can I assign an equation to a variable in MATLAB?

Matlab

Expert Answer

Kshitij Singh ( Staff ) answered . 27/01/2020


The precise answer is to use a string to store the equation but that string isn't useful in Matlab for doing calculations.

Eq = 'a^2+b^2=c^2';
This example stores the equation for the Pythagorean Theorem in the variable called Eq.
But that may not be what you really meant to ask.
KE =@(m,v) m*v.^2/2;
This example is an anonymous function in Matlab. It allows the input of a scalar mass and a vector of velocities and then returns a vector of (classical) kinetic energies. You would use it by a command like:
Energies = KE( 10, 0:0.1:10);
This command stores in the vector Energies all the kinetic energies of a 10 unit mass traveling with velocities from 0 to 10 distance units per time unit (in increments of 0.1).
As another answer mentions, you can also use symbolic variables, provided you buy the symbolic toolbox. This approach is useful for symbolic calculations, but is very slow by comparison to anonymous functions for numerical calculations.