MATLAB Answers

Slow computation speed using piecewise functions

5 views (last 30 days)
JasonJing
JasonJing on 28 May 2020
Edited: Ameer Hamza on 28 May 2020
I'm trying to compute values of 10000 data sets of x using several piecewise functions e.g. f=triangularPulse(0, 1/2, 1, x). The computation speed is very slow within each loop and I'm wondering if it's because the speed under each piecewise function is slower than the regular functions. How to increase the computation speed if I need to use these piecewise functions?
Thanks in advance.

  0 Comments

Sign in to comment.

Accepted Answer

Ameer Hamza
Ameer Hamza on 28 May 2020
Edited: Ameer Hamza on 28 May 2020
Functions such as triangularPulse and piecewise are from the symbolic toolbox, and they can be very slow as compare to floating-point operations. If possible, try to convert it into a numeric function using conditional operators. See the difference in speed of the following two functions
syms x
f(x) = piecewise(x < 0, x^2 + 2*x + sin(x), ...
0 <= x & x < 10, cos(x) + 2*x, ...
10 <= x & x < 100, log(x) + tan(x), ...
100 <= x, x^3 + 2*x);
fun = @(x) (x < 0).*(x.^2 + 2*x + sin(x)) + ...
(0 <= x & x < 10).*(cos(x) + 2*x) + ...
(10 <= x & x < 100).*(log(x) + tan(x)) + ...
(100 <= x).*(x.^3 + 2*x);
xv = 1:500;
t1 = timeit(@() f(xv))
t2 = timeit(@() fun(xv))
Result
>> t1
t1 =
0.6015
>> t2
t2 =
5.0506e-05
>> t1/t2
ans =
1.1909e+04
About 11909 speed gain.

More Answers (0)