Karim
Karim

Reputation: 302

substitute constant to a formula matlab

I define in MATLAB:

syms k2 k3;
k1 = k2/k3;

Where k2 and k3 are symbolic variables. Then typing k1 gives the output:

k1 =

k2/k3

Assign constant value for k2 and k3:

k2 = 1; k3 = 2;

Then I type in matlab commandline:

>> k1

k1 =

k2/k3

Is there any command which shows the result k1 = 1/2 = 0.5 without using the subs function? In the case my formulas have a lot of variables, it is inconvenient to use subs.

Upvotes: 0

Views: 273

Answers (1)

Wolfie
Wolfie

Reputation: 30047

You want to use eval(k1)

syms k2 k3;
k1 = k2/k3;

eval(k1) % output k1 = k2/k3

k2 = 1;

eval(k1) % output k1 = 1/k3

k3 = 2;

eval(k1) % output ans = 0.5

k1       % output k1 = k2/k3

Edit: It's been pointed out in the comments that subs works in the same way (and may be preferable). From the subs documentation:

subs(s) returns a copy of s replacing symbolic variables in s with their values obtained from the calling function and the MATLAB® workspace

So you can use subs(k1) in the same way as I've used eval(k1) above. It gives the same outputs for the first two examples, with the last example taking advantage of the result's exact fractional form as shown.

subs(k1) % ouput ans = 1/2

Upvotes: 2

Related Questions