matlabvariablescommandworkspacesymbolic-references

Symbolic declaration of variables in Matlab


I would like to write my variables as operations between other variables.

For instance if I put a = c + b then value that a keeps inside is the numeric result of the operation of a sum between c and b.

If c = 4 and b = 2 then, the value that a keeps is 6.

But I would like that a keeps the symbolic expression instead of the numeric value. and every time I write a in the command windows, matlab cacht the numeric value of c and the numeric value of b of the worspace variable and a sum them.

Normally if you write a, matlab displays the numeric value that is in this variable. Does anyone know how to do this?


Solution

  • You can do this using the symbolic toolbox. Here's an example:

    syms a b c %# declare a b c to be symbolic variables
    a = b + c;
    
    b=3;c=4; %# now set values for b and c
    eval(a)  %# evaluate the expression in a
    
    ans =
    
        7
    
    b=5;c=9; %# change the values of b and c
    eval(a)
    
    ans =
    
        14
    

    So the definition of a is still b + c (you can check this by typing a at the command window) and when you evaluate it using eval, it uses the current value of b and c to calculate a. Note that b and c are no longer symbolic variables and are converted to doubles. However a still is, and the definition holds because by default, the expressions in symbolic variables are held unevaluated.