Jacobian of equation with left and right hand sides

9 Ansichten (letzte 30 Tage)
Daniel
Daniel am 9 Jul. 2013
Bearbeitet: Karan Gill am 17 Okt. 2017
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 Kommentare
Matt Kindig
Matt Kindig am 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 am 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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Daniel
Daniel am 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 Kommentar
Karan Gill
Karan Gill am 9 Mai 2017
Starting R2017a, The "lhs" and "rhs" functions are available. See my answer below.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (2)

Matt J
Matt J am 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 am 9 Mai 2017
Bearbeitet: Karan Gill am 17 Okt. 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

Kategorien

Mehr zu Symbolic Math Toolbox finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by