{"id":226,"date":"2010-04-08T12:03:10","date_gmt":"2010-04-08T12:03:10","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/2010\/04\/08\/odes-from-symbolic-to-numeric-code\/"},"modified":"2010-04-06T12:05:02","modified_gmt":"2010-04-06T12:05:02","slug":"odes-from-symbolic-to-numeric-code","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2010\/04\/08\/odes-from-symbolic-to-numeric-code\/","title":{"rendered":"ODEs, from Symbolic to Numeric Code"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\r\n   <introduction>\r\n      <p>In a recent post on <a href=\"https:\/\/blogs.mathworks.com\/loren\/2010\/03\/25\/solving-ordinary-differential-equations\/\">solving ODEs<\/a>, the reader Jason wondered if there was a way to do away with the manual algebraic steps using <a href=\"https:\/\/www.mathworks.com\/products\/symbolic\/\">Symbolic Math Toolbox<\/a>. There currently isn't a canned way to do it so the result is a MATLAB program, but you can do so in <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2010a\/toolbox\/mupad\/index.html\">MuPAD<\/a>, the symbolic engine for Symbolic Math Toolbox.  For now, I want to show you how you might generate the ODE solution in the\r\n         case where MuPAD finds a closed-form solution.\r\n      <\/p>\r\n   <\/introduction>\r\n   <h3>Contents<\/h3>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"#1\">Define Symbolic Variables<\/a><\/li>\r\n         <li><a href=\"#2\">Solve the System<\/a><\/li>\r\n         <li><a href=\"#4\">Convert Solution from MuPAD<\/a><\/li>\r\n         <li><a href=\"#6\">Set Values for Mass and Spring Constant<\/a><\/li>\r\n         <li><a href=\"#8\">Plot the Solution<\/a><\/li>\r\n         <li><a href=\"#9\">All Well and Good IF ...<\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>Define Symbolic Variables<a name=\"1\"><\/a><\/h3>\r\n   <p>Let's first define the variables we need to describe the equations for a simple harmonic oscillator, using the same notation\r\n      as the post linked above.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">syms <span style=\"color: #A020F0\">x<\/span> <span style=\"color: #A020F0\">t<\/span> <span style=\"color: #A020F0\">m<\/span> <span style=\"color: #A020F0\">k<\/span><\/pre><h3>Solve the System<a name=\"2\"><\/a><\/h3>\r\n   <p>Using the function <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2010a\/toolbox\/symbolic\/dsolve.html\"><tt>dsolve<\/tt><\/a>, we find the solution.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">sol = dsolve(<span style=\"color: #A020F0\">'m*D2x+k*x(t)'<\/span>,<span style=\"color: #A020F0\">'x(0) = 0'<\/span>,<span style=\"color: #A020F0\">'Dx(0) = 1'<\/span>,<span style=\"color: #A020F0\">'t'<\/span>);<\/pre><p>Reformat the solution display suitable for posting.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">csol = char(sol);\r\ndisp(csol(1:45))\r\ndisp(csol(46:end))<\/pre><pre style=\"font-style:oblique\">(m*exp((t*(-k*m)^(1\/2))\/m))\/(2*(-k*m)^(1\/2)) \r\n- m\/(2*exp((t*(-k*m)^(1\/2))\/m)*(-k*m)^(1\/2))\r\n<\/pre><h3>Convert Solution from MuPAD<a name=\"4\"><\/a><\/h3>\r\n   <p>Using <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2010a\/toolbox\/symbolic\/matlabfunction.html\"><tt>matlabFunction<\/tt><\/a>, I next generate a function handle to a MATLAB version of the solution.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">f = matlabFunction(sol);<\/pre><p>Again, reformat expression to display more nicely in post.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">cf = func2str(f);\r\ndisp(cf(1:65))\r\ndisp([<span style=\"color: #A020F0\">'       '<\/span>, cf(66:end)])<\/pre><pre style=\"font-style:oblique\">@(k,m,t)m.*exp((t.*sqrt(-k.*m)).\/m).*1.0.\/sqrt(-k.*m).*(1.0.\/2.0)\r\n       -m.*exp(-(t.*sqrt(-k.*m)).\/m).*1.0.\/sqrt(-k.*m).*(1.0.\/2.0)\r\n<\/pre><h3>Set Values for Mass and Spring Constant<a name=\"6\"><\/a><\/h3>\r\n   <p>I'm using the same values for <tt>k<\/tt> and <tt>m<\/tt> that I used in the referenced post.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">k = 10;\r\nm = 1;<\/pre><p>I'm now creating a short-hand function with the values for <tt>k<\/tt> and <tt>m<\/tt> set so I can plot the result.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">fnew = @(t) f(k,m,t);<\/pre><h3>Plot the Solution<a name=\"8\"><\/a><\/h3><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">t = 0:0.01:10;\r\nplot(t,fnew(t))<\/pre><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/loren\/226\/symODE_01.png\"> <h3>All Well and Good IF ...<a name=\"9\"><\/a><\/h3>\r\n   <p>That's all well and good if MuPAD can find an analytic solution to the differential equation.  For now, there is not a way\r\n      to automatically generate a MATLAB program for the system of equations defining the ODE suitable for solving numerically.\r\n       MuPAD itself has numerical ODE solvers which may be suitable.  Do you have problems that straddle the symbolic and numerical\r\n      worlds?  How do you handle them?  Let me know <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=226#respond\">here<\/a>.\r\n   <\/p><script language=\"JavaScript\">\r\n<!--\r\n\r\n    function grabCode_9855aae5ef0a44cda915819e6e464356() {\r\n        \/\/ Remember the title so we can use it in the new page\r\n        title = document.title;\r\n\r\n        \/\/ Break up these strings so that their presence\r\n        \/\/ in the Javascript doesn't mess up the search for\r\n        \/\/ the MATLAB code.\r\n        t1='9855aae5ef0a44cda915819e6e464356 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 9855aae5ef0a44cda915819e6e464356';\r\n    \r\n        b=document.getElementsByTagName('body')[0];\r\n        i1=b.innerHTML.indexOf(t1)+t1.length;\r\n        i2=b.innerHTML.indexOf(t2);\r\n \r\n        code_string = b.innerHTML.substring(i1, i2);\r\n        code_string = code_string.replace(\/REPLACE_WITH_DASH_DASH\/g,'--');\r\n\r\n        \/\/ Use \/x3C\/g instead of the less-than character to avoid errors \r\n        \/\/ in the XML parser.\r\n        \/\/ Use '\\x26#60;' instead of '<' so that the XML parser\r\n        \/\/ doesn't go ahead and substitute the less-than character. \r\n        code_string = code_string.replace(\/\\x3C\/g, '\\x26#60;');\r\n\r\n        author = 'Loren Shure';\r\n        copyright = 'Copyright 2010 The MathWorks, Inc.';\r\n\r\n        w = window.open();\r\n        d = w.document;\r\n        d.write('<pre>\\n');\r\n        d.write(code_string);\r\n\r\n        \/\/ Add author and copyright lines at the bottom if specified.\r\n        if ((author.length > 0) || (copyright.length > 0)) {\r\n            d.writeln('');\r\n            d.writeln('%%');\r\n            if (author.length > 0) {\r\n                d.writeln('% _' + author + '_');\r\n            }\r\n            if (copyright.length > 0) {\r\n                d.writeln('% _' + copyright + '_');\r\n            }\r\n        }\r\n\r\n        d.write('<\/pre>\\n');\r\n      \r\n      d.title = title + ' (MATLAB code)';\r\n      d.close();\r\n      }   \r\n      \r\n-->\r\n<\/script><p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><br><a href=\"javascript:grabCode_9855aae5ef0a44cda915819e6e464356()\"><span style=\"font-size: x-small;        font-style: italic;\">Get \r\n            the MATLAB code \r\n            <noscript>(requires JavaScript)<\/noscript><\/span><\/a><br><br>\r\n      Published with MATLAB&reg; 7.10<br><\/p>\r\n<\/div>\r\n<!--\r\n9855aae5ef0a44cda915819e6e464356 ##### SOURCE BEGIN #####\r\n%% ODEs, from Symbolic to Numeric Code\r\n% In a recent post on\r\n% <https:\/\/blogs.mathworks.com\/loren\/2010\/03\/25\/solving-ordinary-differential-equations\/\r\n% solving ODEs>, the reader Jason wondered if there was a way to do away\r\n% with the manual algebraic steps using \r\n% <https:\/\/www.mathworks.com\/products\/symbolic\/ Symbolic Math Toolbox>.\r\n% There currently isn't a canned way to do it so the result is a MATLAB\r\n% program, but you can do so in\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2010a\/toolbox\/mupad\/index.html\r\n% MuPAD>, the symbolic engine for Symbolic Math Toolbox.  For now, I want\r\n% to show you how you might generate the ODE solution in the case where\r\n% MuPAD finds a closed-form solution.\r\n%% Define Symbolic Variables\r\n% Let's first define the variables we need to describe the equations for a\r\n% simple harmonic oscillator, using the same notation as the post linked\r\n% above.\r\nsyms x t m k\r\n%% Solve the System\r\n% Using the function\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2010a\/toolbox\/symbolic\/dsolve.html |dsolve|>,\r\n% we find the solution.\r\nsol = dsolve('m*D2x+k*x(t)','x(0) = 0','Dx(0) = 1','t');\r\n%%\r\n% Reformat the solution display suitable for posting.\r\ncsol = char(sol);\r\ndisp(csol(1:45))\r\ndisp(csol(46:end))\r\n%% Convert Solution from MuPAD\r\n% Using\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2010a\/toolbox\/symbolic\/matlabfunction.html |matlabFunction|>,\r\n% I next generate a function handle to a MATLAB version of the solution.\r\nf = matlabFunction(sol);\r\n%%\r\n% Again, reformat expression to display more nicely in post.\r\ncf = func2str(f);\r\ndisp(cf(1:65))\r\ndisp(['       ', cf(66:end)])\r\n%% Set Values for Mass and Spring Constant\r\n% I'm using the same values for |k| and |m| that I used in the referenced\r\n% post.\r\nk = 10;\r\nm = 1;\r\n%%\r\n% I'm now creating a short-hand function with the values for |k| and |m|\r\n% set so I can plot the result.\r\nfnew = @(t) f(k,m,t);\r\n%% Plot the Solution\r\nt = 0:0.01:10;\r\nplot(t,fnew(t))\r\n%% All Well and Good IF ...\r\n% That's all well and good if MuPAD can find an analytic solution to the\r\n% differential equation.  For now, there is not a way to automatically\r\n% generate a MATLAB program for the system of equations defining the ODE\r\n% suitable for solving numerically.  MuPAD itself has numerical ODE solvers\r\n% which may be suitable.  Do you have problems that straddle the symbolic\r\n% and numerical worlds?  How do you handle them?  Let me know\r\n% <https:\/\/blogs.mathworks.com\/loren\/?p=226#respond here>.\r\n\r\n##### SOURCE END ##### 9855aae5ef0a44cda915819e6e464356\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\n   \r\n      In a recent post on solving ODEs, the reader Jason wondered if there was a way to do away with the manual algebraic steps using Symbolic Math Toolbox. There currently isn't a canned way... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2010\/04\/08\/odes-from-symbolic-to-numeric-code\/\">read more >><\/a><\/p>","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[25,31,38],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/226"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/users\/39"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/comments?post=226"}],"version-history":[{"count":0,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/226\/revisions"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=226"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=226"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=226"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}