Question

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?

Was it helpful?

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.

OTHER TIPS

If you don't have the symbolic toolbox, you could use an anonymous function to achieve a similar result.

b=2; c=4; 
a=@()(evalin('caller','b+c')); 
a(), 

ans =

     6

b=1; 

a()


ans =

     5

Not ideal but may be helpful.

You could make this easier with the following function:

function [ anonFunction ] = AnonEval( expression )
%AnonEval Create an anonymous function that evaluates an expression
   anonFunction = @()(evalin('caller',expression)); 
end

b=2,c=4, 
a=AnonEval('b+c'); 
a(),
b=1; 
a()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top