Reputation: 21662
How to get handle to piece-wise functon in Matlab, for example
function f= AnaliticalF(t1,t2,t,curve)
%solved in Maxima
%solve([a3*t1^3+a2*t1^2+a1*t1+a0= L1, a3*t2^3+a2*t2^2+a1*t2+a0= L2, 3*a3*t1^2+2*a2*t1+a1= 0, 3*a3*t2^2+2*a2*t2+a1= 0],[a3,a2,a1,a0]);
L1= curve(t1);
L2= curve(t2);
if (t <= t1)
f= @(t)L1;
elseif(t >= t2)
f= @(t)L2;
else
a3=-(2*L1-2*L2)/(-t2^3+3*t1*t2^2-3*t1^2*t2+t1^3);
a2=(-3*t2*L2-3*t1*L2+(3*t2+3*t1)*L1)/(-t2^3+3*t1*t2^2-3*t1^2*t2+t1^3);
a1=-(6*t1*t2*L1-6*t1*t2*L2)/(-t2^3+3*t1*t2^2-3*t1^2*t2+t1^3);
a0=(-3*t1^2*t2*L2+t1^3*L2+(3*t1*t2^2-t2^3)*L1)/(-t2^3+3*t1*t2^2-3*t1^2*t2+t1^3);
f= @(t)a3*t^3 + a2*t^2 + a1*t + a0;
end
end
then I want to apply function to array of elements:
f= AnaliticalF(t1,t2,t,curve);
y= arrayfun(f,trange);
but problem is that I need to specify t in AnaliticalF(t1,t2,t,curve)
, but I want it t parameter free.
So I need some 'smart' handle of function f such as call f(100) it can determine which part of piece-wise function to use without specifying parameter t.
Upvotes: 0
Views: 182
Reputation: 1275
You can use indicator functions! For example if if you want the function f(t) = t when t < 0 and f(t) = t^2 when t >= 0, then you can define:
f = @(t) t*(t<0) + t^2*(t>=0);
This can of course easily be generalized to more advanced functions like the one of yours!
I hope this solves your problem.
EDIT: I decided to throw in the solution for your function:
function f= AnaliticalF(t1,t2,curve)
L1= curve(t1);
L2= curve(t2);
a3=-(2*L1-2*L2)/(-t2^3+3*t1*t2^2-3*t1^2*t2+t1^3);
a2=(-3*t2*L2-3*t1*L2+(3*t2+3*t1)*L1)/(-t2^3+3*t1*t2^2-3*t1^2*t2+t1^3);
a1=-(6*t1*t2*L1-6*t1*t2*L2)/(-t2^3+3*t1*t2^2-3*t1^2*t2+t1^3);
a0=(-3*t1^2*t2*L2+t1^3*L2+(3*t1*t2^2-t2^3)*L1)/(-t2^3+3*t1*t2^2-3*t1^2*t2+t1^3);
f = @(t) (t <= t1)*L1 + (t >= t2)*L2 + ((t > t1)&(t<t2))*(a3*t^3 + a2*t^2 + a1*t + a0);
end
Upvotes: 1