Is there a way to speed up the computation of a piecewise defined function?
7 views (last 30 days)
Show older comments
Hello,
I try to create a polar which is piecewise defined by polynomic functions and trigonometric functions. My goal is that for any input x value the y value of the polar is being returned.
I have tried two different versions of doing this, both seem to be quite slow. Is there a faster way to achieve it?
Option 1: Create a structure or a vector with numeric values at certain x/y points. After that, interpolate (if necessary) to return the y values.
Option 2: Using the Symbolic Math toolbox and piecewise() to create the polar.
In my project, the polynomic and trigonometric functions itself depend on other piecewise defined functions, which I guess slows the symbolic solution down even more. Anyway, I feel like it should be faster to numerically solve it with double precision at interpolation points and interpolate afterwards to achieve a continuous function.
Still though, it is not as fast as I wish it to be (I would like to use it for an autopilot). Any suggestions for a different approach?
Thank you!
x_input=-2.12345;
%Option 1
n=-10;
while(n<=10)
struct.x(n+11)=n;
if n<-5
struct.y(n+11)=-2;
end
if (-5<n) & (n<5)
struct.y(n+11)=sin(n);
end
if n>5
struct.y(n+11)=n;
end
n=n+1;
end
Fo=griddedInterpolant(struct.x(:),struct.y(:),'spline');
y_output=Fo(x_input);
%Option 2
syms y(x)
y(x) = piecewise(x < -5,-2,-5<x<5,sin(x),x>5,x);
y_output2=double(y(x_input));
0 Comments
Accepted Answer
Dyuman Joshi
on 8 Jun 2023
Edited: Dyuman Joshi
on 8 Jun 2023
Logical indexing would be my best bet -
x_input=-2.12345;
n = -10:10;
%x is same as n
%preallocate y
y = zeros(size(n));
%conditions
idx1 = n<-5;
idx2 = n>-5 & n<5;
idx3 = n>5;
%also, the values at n==5 and n==-5 are zero, as you have include these points
%in any of the conditions
y(idx1) = -2;
y(idx2) = sin(n(idx2));
y(idx3) = n(idx3);
Fo=griddedInterpolant(n,y,'spline');
y_output=Fo(x_input)
Imo, it's better to work with a single data type throughout the code. Conversion from 1 data type to another might decrease the code efficiency.
As for the polynomic and trigonometric functions (which are part of your project), you can define them as functions and use accordingly.
See Also
Categories
Find more on Assembly in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!