Jacobian of equation with left and right hand sides

8 views (last 30 days)
I have a program where the user inputs an equation in the form of a string:
'2*a + 3*b = 5*c' % (just an example, it can be any linear equation)
in sequence I list the variables and take the Jacobian:
allvars = symvar(input);
J = jacobian(input, allvars);
However, because of the "=" in the equation my output is:
J = [ 2 = 0, 3 = 0, 0 = 5]
and instead I *need*** it to be:
J = [ 2, 3, -5]
How can I solve this? Having the user input '2*a + 3*b - 5*c' is not an option.
I tried looking for a rhs/lhs (right/left hand side) function but there aren't any, the @children function is available only in R2012a and greater.
  2 Comments
Matt Kindig
Matt Kindig on 9 Jul 2013
Hmmm, interesting question. Maybe you'll need to parse the input string and move everything to the left hand side first. Something like this might work:
input = '2*a + 3*b = 5*c'; %for example
sides= regexp(input, '=', 'split'); %chop by equals sign
%replace with expression where everything is on left hand side
modified = sprintf('%s - (%s)', sides{1}, sides{2});
allvars = symvar(modified);
J = jacobian( modified, allvars); %this should give the correct answer.
Daniel
Daniel on 10 Jul 2013
Hi Matt,
Thank you for your swift reply.
Currently I'm doing something like this as a temporary fix but I was hoping to achieve a solution using the symbolic toolbox.

Sign in to comment.

Accepted Answer

Daniel
Daniel on 24 Feb 2014
Oh, I didn't realize I hadn't given this thread closure.
I went with Matt Kindig's approach of making the symbolic equation completely left sided, this is a minimum example:
sumblocks = {'y = x1 + x2'}
sides = regexp(sumblocks, '=', 'split');
for i=1:size(sides,1)
sumblocks{i} = sprintf('%s - (%s)', sides{i}{1}, sides{i}{2});
end
The output given in "sumblocks" will be a left-sided equation.
  1 Comment
Karan Gill
Karan Gill on 9 May 2017
Starting R2017a, The "lhs" and "rhs" functions are available. See my answer below.

Sign in to comment.

More Answers (2)

Matt J
Matt J on 9 Jul 2013
Could you do something like
>> str='2*a + 3*b = 5*c';
>> newstr=[strrep(str,'=','-(') , ')']
newstr =
2*a + 3*b -( 5*c)

Karan Gill
Karan Gill on 9 May 2017
Edited: Karan Gill on 17 Oct 2017
Starting R2017a, The "lhs" and "rhs" functions are available. See:
Here's a toy example.
>> syms a b c d
>> eqn = a+b == c+d
eqn =
a + b == c + d
>> lhs(eqn)
ans =
a + b
>> rhs(eqn)
ans =
c + d

Categories

Find more on Symbolic Math Toolbox in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!