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.
Best Answer