Code covered by the BSD License

# SymPy CAS in MATLAB

### Jonathan Lister (view profile)

23 Jul 2013 (Updated )

Enables using Python's SymPy CAS in MATLAB

symeval(sympy_fun,fstr,varargin)
```function result = symeval(sympy_fun,fstr,varargin)
%SYMEVAL is a function to utilize the capabilities of Symbolic Python
% as a poor man's symbolic toolbox.
%
% Syntax:
%    result = symeval(sympy_fun,fexpr,arg1,arg2,arg3,...)
%
% Description:
%    This function utilizes Python's SymPy module to provide symbolic
%    capabilities for those of us who do not have the Symbolic Toolbox at
%    our disposal. EXPECT THIS TO BE SLOW.  This is still a work in
%    progress.
%
% Requirements:
%    1. A local Python installation with the SymPy module installed.  It is
%       recommended that you install a Python distribution such as
%
%    2. The included Python script symeval.py must be in your working dir.
%
% Input:
%     sympy_fun = this is the sympy function you wish to utilize
%                 Note: for a list of sympy funcitons please see
%                       http://docs.sympy.org/0.7.3/tutorial/index.html
%          fstr = a string expression of the function you wish to evaluate.
%                 Note: symbolic variables must be limited to x,y,z
%                       you can expand this by editing symeval.py
%      varargin = a list of arguments to pass to the sympy function
%
% Output:
%     result = the result of the Python sympy function with operators
%              converted to MATLAB operators
%
% Examples:
%   %find the derrivative of a function
%   result = symeval('diff','sin(x)','x');
%   f = inline(result) % to create an inline funciton that you can evaluate
%   f = vectorize(inline(result)); % a vectorized inline function.
%
%   %verify differentiation and integration
%   result1 = symeval('diff','sin(x)/x','x')
%   % result1 =
%   % cos(x)/x-sin(x)/x^2
%
%   result2 = symeval('integrate',result1,'x')
%   % result =
%   % sin(x)/x
%
% Bugs and suggestions:
%    Please send to jonathan lister (mechanical.engineer78 at gmail.com)
%
% Change log:
%    2013-07-23: first version
%

evalstr = ['python symeval.py ' sympy_fun ' ' fstr];
for i=1:numel(varargin)
evalstr = [evalstr ' ' varargin{i}]; %#ok<AGROW>
end
evalstr = strrep(evalstr,'^','**');
[~, result] = system(evalstr);
result = strrep(result,'**','^');
result = strrep(result,' ','');
end

%% Python script symeval.py source
%{
import sys
from sympy import *
x,y,z = symbols('x,y,z')
args = sys.argv
evalstr = args[1] + '('
n = len(args)
indx = range(n)
for i in indx:
if i > 1:
evalstr = evalstr + args[i] + ','
else:
l = len(evalstr)
evalstr = evalstr[0:l-1] #remove the last ','
evalstr = evalstr + ')' #close the command
result = eval(evalstr)  #evaluate the command
print(result)           #print the result
%}
```