Slow computation speed using piecewise functions
8 views (last 30 days)
Show older comments
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
Accepted Answer
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.
2 Comments
More Answers (0)
See Also
Categories
Find more on Number Theory 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!