Slow computation speed using piecewise functions
8 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
JasonJing
el 28 de Mayo de 2020
Editada: Ameer Hamza
el 28 de Mayo de 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 comentarios
Respuesta aceptada
Ameer Hamza
el 28 de Mayo de 2020
Editada: Ameer Hamza
el 28 de Mayo de 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 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Assumptions en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!