Jacobian of equation with left and right hand sides

10 vues (au cours des 30 derniers jours)
Daniel
Daniel le 9 Juil 2013
Modifié(e) : Karan Gill le 17 Oct 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 commentaires
Matt Kindig
Matt Kindig le 9 Juil 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 le 10 Juil 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.

Connectez-vous pour commenter.

Réponse acceptée

Daniel
Daniel le 24 Fév 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 commentaire
Karan Gill
Karan Gill le 9 Mai 2017
Starting R2017a, The "lhs" and "rhs" functions are available. See my answer below.

Connectez-vous pour commenter.

Plus de réponses (2)

Matt J
Matt J le 9 Juil 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 le 9 Mai 2017
Modifié(e) : Karan Gill le 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

Catégories

En savoir plus sur Symbolic Math Toolbox dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by