Slow computation speed using piecewise functions

조회 수: 9 (최근 30일)
JasonJing
JasonJing 2020년 5월 28일
편집: Ameer Hamza 2020년 5월 28일
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.

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 5월 28일
편집: Ameer Hamza 2020년 5월 28일
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
JasonJing
JasonJing 2020년 5월 28일
Perfect. thanks!
Ameer Hamza
Ameer Hamza 2020년 5월 28일
I am glad to be of help!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Assumptions에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by