Why do trigonometric functions in MATLAB require different computation times when provided the same-sized input?
4 views (last 30 days)
Show older comments
MathWorks Support Team
on 27 Jun 2009
Edited: MathWorks Support Team
on 27 Mar 2023
I see that the third and fifth cases take significantly longer, approximately 6 times longer, than the other cases even though they have the same size input.
varA = rand(1,78);
c = -256:255;
w = -256:255;
x = -256:255;
y = -256:255;
z = -256:255;
z = z/(1000*rand(1));
for ii = 1:50
%Case 1
% Control case
twopicA = 2 * pi * c' * varA;
ccos = cos(twopicA); % Time 1
csin = sin(twopicA); % Time 2
%Case 2
% Incrementing + case
w = w + 1;
twopiwA = 2 * pi * w' * varA;
wcos = cos(twopiwA); % Time 1
wsin = sin(twopiwA); % Time 2
%Case 3
% Incrementing + (varying integer) case
x = x + 10000*ii;
twopixA = 2 * pi * x' * varA;
xcos = cos(twopixA); % Time 1
xsin = sin(twopixA); % Time 2
%Case 4
% Incrementing + (non-integer) case
y = y + rand(1);
twopiyA = 2 * pi * y' * varA;
ycos = cos(twopiyA); % Time 1
ysin = sin(twopiyA); % Time 2
%Case 5
% Incrementing + (varying-non-integer) case
z = z + 10000*ii*rand(1);
twopizA = 2 * pi * z' * varA;
zcos = cos(twopizA); % Time 1
zsin = sin(twopizA); % Time 2
end
Accepted Answer
MathWorks Support Team
on 26 Mar 2023
Edited: MathWorks Support Team
on 27 Mar 2023
This is the expected behavior. MATLAB uses the fdlibm library for trigonometric function computation. The trigonometric functions in the fdlibm library perform range checking, handle edge cases and reduce inputs. As a result, the computational cost can vary for the same function with the same size input array.
For example, in certain cases when given inputs with a range from 0 to 10*pi these library functions will need to initially scale the inputs back to the range 0 to 2*pi.
For more information regarding the fdlibm library refer to
0 Comments
More Answers (0)
See Also
Categories
Find more on Dates and Time 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!