Is element-wise multiplication or element-wise squaring faster?

조회 수: 9 (최근 30일)
Ted
Ted 2013년 9월 25일
I have a matrix A for which I need its individual elements squared. Which of the following is faster?
% This... >> B = A .* A;
% Or this? >> B = A .^ 2;
Anyone know which of these is faster? Some initial tests suggest the direct squaring is marginally faster... but I'd like to know why.
Thanks!

채택된 답변

Kelly Kearney
Kelly Kearney 2013년 9월 25일
A slightly more robust timing test, using timeit:
n = 1:100:1000;
t = zeros(length(n),2);
for ii = 1:length(n)
a = rand(n(ii));
t(ii,1) = timeit(@() a.*a);
t(ii,2) = timeit(@() a.^2);
end
plot(n, t, 'marker', '.');
legend('*', '^');
Playing around with the values of n give me different results. For small matrices (n ~ 1-10), times is faster. For larger matrices (n ~ 100-4500), power is faster. After this point, the two converge to nearly identical run times.
Not sure on the why, since both function are built-ins. But running similar tests to the above should give you a good idea of how your computer will respond for the matrix sizes relevant to your problem.

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by