Array of symbolic vectors substitution issue - MATLAB missing ability to substitute exactly

Viewed 80

I have an equation of symbolic vectors (in fact, usually many equations) that I'd like to substitute with a different symbolic vector. I would like MATLAB to substitute the equation with the new symbolic variables such that none of the old ones remain. I have been using the subs function, but it seems to jump at the earliest chance to use a substitution, rather than substituting exactly.

Here is an example of what I mean:

>> M = sym('m',[1,4]).'

M =

 m1
 m2
 m3
 m4

>> N = sym('n',[1,4]).'

N =

 n1
 n2
 n3
 n4

>> eqn = N(2,1) + 2*N(3,1) - 4*N(4,1)

eqn =

n2 + 2*n3 - 4*n4

>> relation = [N(1,1);N(4,1); N(3,1) - 2*N(4,1); N(2,1)]


relation =

        n1
        n4
 n3 - 2*n4
        n2

>> subs(eqn,relation,M)

ans =

m4 - 4*m2 + 2*n3

By hand, I can clearly see that eqn == m4 + 2*m3 exactly. Yet when I ask MATLAB to substitute, I am still left with +2*n3 in the equation.

I have searched around for similar issues to little avail, how can I make MatLab substitute ALL occurrences of n in my equation?

I will usually have many such equations, and I know that it is possible to substitute with m's exactly.

1 Answers

You can use the inverse relation, instead of using M expressed by N you can get the inverse relation - N expressed by M. This is simpler for subs because you want to replace N:

M = sym('m',[1,4]).';
N = sym('n',[1,4]).';
eqn = N(2,1) + 2*N(3,1) - 4*N(4,1);
relation = [N(1,1);N(4,1); N(3,1) - 2*N(4,1); N(2,1)];

% Get invers of relation, N => M
invRelation = struct2array(solve(M - relation, N)).';
newEqn = subs(eqn,N,invRelation);

Result:

relation =
 
        n1
        n4
 n3 - 2*n4
        n2
 
 
invRelation =
 
        m1
        m4
 2*m2 + m3
        m2
 
 
eqn =
 
n2 + 2*n3 - 4*n4
 
 
newEqn =
 
2*m3 + m4

Another simple example were subs fails

I'm not sour sure if the limitations of subs are documented, I did not find any, but here is another very simple example were subs fails:

syms x y
eun = x;
subs1 = subs(x,x,-y)
subs2 = subs(x,-x,y)

Output:

subs1 =
 
-y
 
 
subs2 =
 
x
Related