Is there a way to speed up the computation of a piecewise defined function?

7 views (last 30 days)
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));

Accepted Answer

Dyuman Joshi
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)
y_output = -0.8546
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.

More Answers (1)

Matt J
Matt J on 8 Jun 2023
Edited: Matt J on 8 Jun 2023
Use logical indexing,
%Option 1.1
x=-10:10;
y=x;
y(x<=-5)=-2;
p=abs(x)<5;
y(p)=sin(x(p));
struct.x=x;
struct.y=y;

Products


Release

R2023a

Community Treasure Hunt

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

Start Hunting!