5

I want to eliminate variables from an equation using MATLAB. For example, lets consider the following equations:

p = (m + n)
q = (m - n)
r = (m^3 - n^3)

Now, r could be expressed in terms of p and q by entirely eliminating m and n like this: r = (3*p^2*q + q^3)/4.

This can be achieved in Mathematica using the following method:

Eliminate[{p == (m + n), q == (m - n), r == (m^3 - n^3)}, {m, n}]

How can I get the same result in MATLAB if it is possible at all. Switching between different applications just for this is very inconvenient.

iKnowNothing
  • 175
  • 11

2 Answers2

2
% Declare symbolic variables
syms m n p q

% Solve m,n 
s1=solve(m+n-p==0,m-n-q==0,m,n);

% Substitute variables with obtained solution
r = (m^3 - n^3);
r2=subs(subs(r,m,s.m),n,s.n);

% simplify answer
r3=simplify(r2)
Ander Biguri
  • 35,140
  • 11
  • 74
  • 120
  • So the steps that I need to follow are: solve the equations in terms of desired variables and then substitute them in the final equation. I am guessing the same would apply for three or more variables as well. :) – iKnowNothing Jul 13 '18 at 13:13
  • 1
    @iKnowNothing yes indeed. This is not 2 variable specific. MATLABs symbolic toolbox is not as advanced as Mathematica, so you need to think which steps do you need to take and program them one by one. – Ander Biguri Jul 13 '18 at 13:17
1

Solve the both equation and find the values for p and q. Then subs function will give the solution by substituting m & n by p & q. More information available here

eqn1 = r == (m^3 - n^3);
eqn2 = p == (m + n);
eqn3 = q == (m - n);

eqn4 = isolate(eqn2,m);  
eqn5 = isolate(eqn3,m);
eqn6 = rhs(eqn2) == rhs(eqn3);
eqn6 = isolate(eqn4,n);   %solving for n
eqn7 = subs(eqn4,lhs(eqn6),rhs(eqn6)); %solving for m

eqn1 = subs(eqn1,lhs(eqn6),rhs(eqn6));  %substituting n
eqn1 = subs(eqn1,lhs(eqn7),rhs(eqn7));  %subtituting m
amahmud
  • 434
  • 4
  • 14