More efficient symbolic code

1 view (last 30 days)
Given a polynomial in n variables f=f(x1,x2,...,xn) (given by symbolic). I would like to implement a code that takes f and i(for any number from 1 through n-1) and gives the new function P=((1-x(i+1))*f(x1,...,xn)-(1-xi)*f(x1,...x(i+1), xi, ..., xn))/(xi-x(i+1)).
I wrote the following brute force two pieces of code: The first one is to swap to variables, and the second for the isobaric difference
1s code
function [ P ] = swap( f, i )
X=symvar(f);
Y=X;
Y(i)=X(i+1);
Y(i+1)=X(i);
P=subs(f,X,Y);
end
2nd code
function [ P ] = isodiff( f,i )
X=symvar(f);
P=((1-X(i+1))*f-(1-X(i))*swap(f,i))./(X(i)-X(i+1));
P=simplify(P);
end
Is there a more efficient way to solve this problem?

Accepted Answer

Walter Roberson
Walter Roberson on 26 Jun 2015
Edited: Walter Roberson on 26 Jun 2015
Your swap is probably reasonably efficient. About the only other approach I would consider, and only for doing it several times, would be
X = symvar(f);
F = symfun(f, X);
Xc = num2cell(X);
swap = @(i) F(Xc{1:i-1}, Xc{i+1}, Xc{i}, Xc{i+2:end});
There is a subtle difference between this and what you had. When you subs() a new value in, other than the automatic simplifications such as converting 0*x to 0 and moving all numeric terms together, the result is left unevaluated. When you evaluate a symbolic function on a set of parameters, the symbolic engine will re-execute the expressions, evaluating the resulting formula instead of just rewriting it. When you know that all you have done is change variable names and know that none of the variable names have assignments made to them, then you know that re-evaluation is not going to have any effect that rewriting would not have had. But the symbolic engine doesn't know that. After all, you might have substituted in a numeric value.
On the other hand if speed of execution is a primary concern you should probably skip simplify() as that can take an undetermined amount of time while it hunts for potential simplifications.

More Answers (0)

Categories

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

Tags

Community Treasure Hunt

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

Start Hunting!