Split Anonymous Function into Terms - matlab

I am wanting to take a matlab anonymous function of something like #(x) = x + x^2 and split it into a cell array so that
f{1} = #(x) x
f{2} = #(x) x^2
I want to be able to do this with some arbitrary function handle. The best that I have come up with so far is taking in #(x) = x + x^2 as a string and splitting it by the addition signs and appending #(x) to the beginning of this. However, I would like to be able to directly use a function handle as the function argument. It would also be nice as using other variables could lead to some difficulty in the string approach.
I am also considering just taking in a cell array of function handles as an argument, which would be more difficult for the user but easier in my code.
For some background, I'm wanting to do this for some least squares data fitting code that I am writing for a class. This code will be for taking in a model function as an argument and I need to evaluate each term separately for the least squares process. I'm not limiting these models to polynomials and even if a polynomial is the model, I want the option to leave out certain powers in the polynomial. If someone has a better suggestion for taking a model function, that would be great too.
UPDATE: Someone wanted to know what I meant by
I'm not limiting these models to polynomials and even if a polynomial
is the model, I want the option to leave out certain powers in the
polynomial.
For some clarification, I was saying that I didn't want to limit the models to
c0 + c1*x + ... + cn*x^n
in which case I could just take in n as a parameter and create terms from that similar to what happens in polyfit. For example, if I know that my input data fits an even or odd function, I may want one of the following models
c0 + c1*x^2 + c2*x^4 + ... + ck*x^(2k)
c1*x + c2*x^3 + ... + cm*x^(2m-1)
Where k is even and m is odd. Or possibly a model that isn't strictly a polynomial, but keeps the coefficients linear, such as
c0 + exp(x) * ( c1 + c2*x + ... cn*x^(n-1) )

This is an interesting problem. The string should not be split at + signs that are within a parenthesis group. For example, with
f = #(x) x + (x+1)*sqrt(x) + x^2 + exp(x+2);
the string should be split at the first, but not at the second + sign.
This can be accomplished as follows. To detect only + signs that are outside parentheses, add 1 for each opening parenthesis and subtract 1 for each closing parenthesis. Then the desired + signs are those with count 0.
I'm assuming the output should be a cell array of function handles. If it should be a cell array of strings just remove the last line.
F = functions(f);
str = F.function; %// get string from function handle
[pref, body] = regexp(str, '#\(.+?\)', 'match', 'split'); %// pref is the '#(...)' part
body = body{2}; %// body is the main part
ind = cumsum((body=='(')-(body==')'))==0 & body=='+'; %// indices for splitting
body(ind) = '?'; %// '?' will be used as split marker
ff = strcat(pref, strsplit(body, '?')); %// split, and then add prefix
ff = cellfun(#str2func, ff, 'uniformoutput', 0); %// convert strings to functions
Result in this example:
ff{1} =
#(x)x
ff{2} =
#(x)(x+1)*sqrt(x)
ff{3} =
#(x)x^2
ff{4} =
#(x)exp(x+2)

Related

Use of (ilaplace) give different result through sym variable and directly

I have a symbolic variable, which contain, for example:
p =
(9311.0*s + 6.12e9)/(s^2 + 8500.0*s + 3.61e11)
where s - also symbolic.
Then, if I use inverse laplace through variable p, then result is
>>result=vpa(ilaplace(p,s,n),3)
result =
exp(n*(- 4255.0 + 6.01e5*i))*(4666.0 - 5066.0*i) + exp(n*(- 4255.0 - 6.01e5*i))*(4666.0 + 5066.0*i)
But if I put expression directly, I will get what I expect (by formula in Korn's book or by definition):
vpa(ilaplace((9311.0*s + 6.12e9)/(s^2 + 8500.0*s + 3.61e11),s,n),3)
ans =
9311.0*exp(-4255.0*n)*(cos(6.01e5*n) + 1.09*sin(6.01e5*n))
Why? And what should I do to get right answer through variable?
P.S. vpa - is not influenced on main goal. It only left 3 digits in this case after point.
P.S.S. Added more code:
t = tf(linsys1) %linsys1 - from simulink circuit
%get coefficients from transfer function t
[num,den] = tfdata(t);
syms s n real
% convert transfer function to symbolic
t_sym = poly2sym(cell2mat(num),s)/poly2sym(cell2mat(den),s);
functionInMuPad=['partfrac(',char(t_sym),',s,Domain = R_)']; %collect expression in string format
simpleFraction=evalin(symengine,functionInMuPad); % sum of simple fractions (only MuPad allows get denominator of 2nd order)
functionInMuPad2=['op(',char(simpleFraction),')']; %collect expression in string format
vectorOfOperand=evalin(symengine,functionInMuPad2); % vector of simple fractions
for k=1:length(vectorOfOperand)-1
z(k,1)=ilaplace(vectorOfOperand(k),s,n);
end
So, something wrong with vectorOfOperand.
ilaplace(vectorOfOperand(1)) gives complex result, but if copy (ctrl+c) value of vectorOfOperand(1) and make newVariable=Ctrl+V, then ilaplace(newVariable) - it's ok either in command window or in m-file:
bbb =(9313.8202564498255348020392071286*s + 6122529964.4040716985063406588769)/(8500.4056471180697831891961467533*s + s^2 + 360665607284.96754103451618653904);
ilaplace(bbb,s,n)
ans=9311.0*exp(-4255.0*n)*(cos(6.01e5*n) + 1.09*sin(6.01e5*n)) %after vpa
Kind of magic anyway. vectorOfOperand - is sym. I even made this:
vectorOfOperand=char(vectorOfOperand);
vectorOfOperand=sym(vectorOfOperand); it doesn't help..

Make sure MATLAB does not recalculate symbolic expression

I am building (my first...) MatLab program, it needs to differentiate an equations symbolically and then use this solution many many times (with different numeric inputs).
I do not want it to recalculate the symbolic differentiation every time it needs to put in a new set of numeric values. This would probably greatly add to the time taken to run this program (which - given its nature, a numeric optimiser, will probably already be hours).
My question is how can I structure my program such that it will not recalculate the symbolic differentiation?
The class in question is:
function [ result ] = GradOmega(numX, numY, numZ, numMu)
syms x y z mu
omega = 0.5*(x^2+y^2+z^2) + (1-mu)/((x+mu)^2+y^2+z^2)^0.5 + mu/((x+mu-1)^2+y^2+z^2)^0.5;
symGradient = gradient(omega);
%//Substitute the given numeric values back into the funtion
result = subs(symGradient, {x,y,z,mu}, {numX, numY, numZ, numMu});
end
I know that I could just symbolically calculate the derivative and then copy-paste it into the code e.g.
gradX = x + ((2*mu + 2*x)*(mu - 1))/(2*((mu + x)^2 + y^2 + z^2)^(3/2)) - (mu*(2*mu + 2*x - 2))/(2*((mu + x - 1)^2 + y^2 + z^2)^(3/2));
gradY = y - (mu*y)/((mu + x - 1)^2 + y^2 + z^2)^(3/2) + (y*(mu - 1))/((mu + x)^2 + y^2 + z^2)^(3/2);
gradZ = z - (mu*z)/((mu + x - 1)^2 + y^2 + z^2)^(3/2) + (z*(mu - 1))/((mu + x)^2 + y^2 + z^2)^(3/2);
But then my code is a bit cryptic, which is a problem in a shared project.
There is a related query here: http://uk.mathworks.com/matlabcentral/answers/53542-oop-how-to-avoid-recalculation-on-dependent-properties-i-hope-a-mathwork-developer-could-give-me-a
But I'm afraid I couldn't follow the code.
Also I am much more familiar with Java and Python, if that helps explain anything.
You could wrap your function into some kind of Function-Factory, which does not return numerical results, but a function that can be evaluated:
(I had to replace the call syms with sym('mu'), because for some reason it kept calling a mutools function in line omega = .... I did also change the call to gradient to make sure the arguments are in correct order, and mu will be treated as constant.)
function GradOmega = GradOmegaFactory()
x = sym('x');
y = sym('y');
z = sym('z');
mu = sym('mu');
omega = 0.5*(x^2+y^2+z^2) + (1-mu)/((x+mu)^2+y^2+z^2)^0.5 + mu/((x+mu-1)^2+y^2+z^2)^0.5;
symGradient = gradient(omega,{'x','y','z'});
GradOmega = matlabFunction(symGradient, 'vars', {'x','y','z','mu'});
end
Then you would call it via:
GradOmega = GradOmegaFactory();
result1 = GradOmega(numX1, numY1, numZ1, numMu1);
result2 = GradOmega(numX2, numY2, numZ2, numMu2);
result3 = GradOmega(numX3, numY3, numZ3, numMu3);
...
Even better:
You could go even more fancy and use a wrapper function GradOmega which builds such a function inside and makes it persistent, to get the same interface you had with your initial approach. The first time you call the function GradOmega the symbolic expression is evaluated, but on each consecutive call you will only have to evaluate the generated function handle, which means it should be nearly as fast as if you hard-coded it.
function result = GradOmega(numX, numY, numZ, numMu)
persistent numericalGradOmega;
if isempty(numericalGradOmega)
numericalGradOmega = GradOmegaFactory();
end
result = numericalGradOmega(numX, numY, numZ, numMu);
end
Use this like you would use your original version
result = GradOmega(numX, numY, numZ, numMu);
Just copy and paste both functions into a single GradOmega.m file. (GradOmega should be the first function in the file.)
Another tip: You can even evaluate this function using vectors. Instead of calling GradOmega(1,2,3,4) and GradOmega(5,6,7,8) afterwards, you can save the time overhead via the call GradOmega([1,5], [2,6], [3,7], [4,8]) using row vectors.
Yet another tip: To clean up your code even more, you could also put the first lines into a separate symOmega.m file.
function omega = symOmega()
x = sym('x');
y = sym('y');
z = sym('z');
mu = sym('mu');
omega = 0.5*(x^2+y^2+z^2) + (1-mu)/((x+mu)^2+y^2+z^2)^0.5 + mu/((x+mu-1)^2+y^2+z^2)^0.5;
This way you don't have to have a copy of this symbolic expression in every file you use it. This can be beneficial if you also want to evaluate Omega itself, as you then can make use of the same Factory-approach listed in this answer. You would end up with the following files: symOmega.m, Omega.m and GradOmega.m, where only the file symOmega.m has the actual mathematical formula and the other two files make use of symOmega.m.

How can i create a multivariable function in matlab out of matrix data?

but i want to make a program in which i can generate a function of multiple variables that depend on the number of rows of a matrix.
for k = 1:sizel;
f(k)=(alpha(k,1)+(beta(k,1)*p(k))+(gamma(k,1)*p(k)^2));
end
cost=(sum(f))
this is for the purpose of optimization so i need that at the end the variables are declares as p(1),p(2),p(3)... these will be the input for my function.
Note: i dont want to assign values to the variables because this will be done be the optimization algorithm in the optimization toolbox.
here is the complete code
function cost = cost(p) ;
clc
clear
costfunctionconstantsmatrix;
sizel=size(CostFormulaconstants);
alpha=CostFormulaconstants(:,1);
beta=CostFormulaconstants(:,2);
gamma=CostFormulaconstants(:,3);
for k = 1:sizel;
f(k)=(alpha(k,1)+(beta(k,1)*p(k))+(gamma(k,1)*p(k)^2));
end
cost=(sum(f))
end
i used the symbolic approach and i got the correct answer for the cost indeed, i got something like this: (53*p(1))/10 + (11*p(2))/2 + (29*p(3))/5 + p(1)^2/250 + (3*p(2)^2)/500 + (9*p(3)^2)/1000 + 1100. But when i try to specify my function to be optimized in the optimization toolbox it tells me that the variables p are sym and cannot be converted to double. the trouble is how to convert this expression to double so that the optimization algorithm can input values for the variable p(1), p(2) and p(3)
Can you pass the matrix as an argument to the function?
function cost = fcn(my_mat)
[m,n] = size(my_mat);
f = zeros(m,1);
for k = 1:m % for example
f(k)=(alpha(k,1)+(beta(k,1)*p(k))+(gamma(k,1)*p(k)^2));
end
cost = sum(f);
end
Your problem is not entirely clear to me but I believe you wish to generate a series of functions in which the variables alpha, beta, gamma are constants with different values for each function, and the vector p is an argument.
What confuses me in your question is that you use the index k for both the constants and the arguments, which I think is not what you intended to write. Assuming I understand your goal, a solution may make use of function handles.
The notation f(k) = #(p) p(1)+p(2) for example, generates a function that adds p(1) and p(2). Abbreviating CostFormulaconstants to cf, the following would generate a series of functions, one for each row in cf.
for k = 1 : size(cf, 1)
f{k} = #(p) cf(k,1) + cf(k,2)*p(1) + cf(k,3)*p(2)^2;
end
You can supply individual function handles to callers from the optimization toolbox simply with f{3} for the third function, for example. A call to f{3} would look like
a = f{3}([3,4]);
If your functions are indeed all polynomials, polyval may be worth a look as well.
EDIT: After clarification, the problem seems a bit simpler, no need for function handles. Why not simply
function c = cost(p)
c = 0;
cf = [...]; % your coefficients here.
for k = 1 : size(cf, 1)
c = c + cf(k,1) + cf(k,2)*p(k) + cf(k,3)*p(k)^2;
end

Get function handle of fit function in matlab and assign fit parameters

I'm fitting custom functions to my data.
After obtaining the fit I would like to get something like a function handle of my fit function including the parameters set to the ones found by the fit.
I know I can get the model with
formula(fit)
and I can get the parameters with
coeffvalues(fit)
but is there any easy way to combine the two in one step?
This little loop will do the trick:
x = (1:100).'; %'
y = 1*x.^5 + 2*x.^4 + 3*x.^3 + 4*x.^2 + 5*x + 6;
fitobject = fit(x,y,'poly5');
cvalues = coeffvalues(fitobject);
cnames = coeffnames(fitobject);
output = formula(fitobject);
for ii=1:1:numel(cvalues)
cname = cnames{ii};
cvalue = num2str(cvalues(ii));
output = strrep(output, cname , cvalue);
end
output = 1*x^5 + 2*x^4 + 3*x^3 + 4*x^2 + 5*x + 6
The loop needs to be adapted to the number of coefficients of your fit.
Edit: two slight changes in order to fully answer the question.
fhandle = #(x) eval(output)
returns a function handle. Secondly output as given by your procedure doesn't work, as the power operation reads .^ instead of x, which can obviously be replaced by
strrep(output, '^', '.^');
You can use the Matlab curve fitting function, polyfit.
p = polyfit(x,y,n)
So, p contains the coefficients of the polynomial, x and y are the coordinates of the function you're trying to fit. n is the order of the polynomial. For example, n=1 is linear, n=2 is quadratic, etc. For more info, see this documentation centre link. The only issue is that you may not want a polynomial fit, in which case you'll have to use different method.
Oh, and you can use the calculated coefficients p to to re-evaluate the polynomial with:
f = polyval(p,x);
Here, f is the value of the polynomial with coefficients p evaluated at points x.

Linear combination of a string vector (w/functions) and number vector (coefficients)

I'm really new at matlab, and am trying to fit a line or curve to data points for homework (that part is actually done). Now, I want to take this a little further than the homework asked, I have constructed a function that takes in a text file with coordinates and any number of functions (1,x,x^2... e.g.) and determines the coefficients.
So in the end I'm left with two vectors: one with the coefficients: C = [a,b,c] and another one with functions: F = {'1','x','x^2'}, and I'd like to create a linear combination of them: l = a + b*x + c*x^2, to plot the curve on a graph, and for some reason I can't figure out how to get that to work. Is there something obvious I'm overlooking, or do I have to rethink this in some way?
a=1; b=2; c=3;
C=[a,b,c];
CS = cellfun(#num2str,num2cell(C),'uniformoutput',0)
M={'*','*','*'};
F={'1','x','x^2'};
P={' + ',' + ',''};
S=reshape([CS; M; F; P],1,[]);
cat(2,S{:})
Output:
ans =
1*1 + 2*x + 3*x^2
Are you sure you want to print 'a', 'b' and 'c' as chars?