Is it better to use sqrt or ^(1/2) ?
Show older comments
In order to have better performance in terms of computational time, is it better to use sqrt or ^(1/2) ?
Accepted Answer
More Answers (1)
Amarpreet
on 8 Sep 2023
0 votes
Both these operations result in different values when operated on a matrix, so that may also be considered while using the functions.sqrt gives square root of each element, while the pow function operates on the whole matrix.
2 Comments
For the computation of the matrix square root, have you compared the speed with sqrtm() function as well?
M = diag([4 9 25])
Mr = sqrtm(M)
N = 5:5:100;
t_sqrt = zeros(length(N),1) ; t_sqrt1 = t_sqrt; t_pow = t_sqrt; t_pow1 = t_sqrt;
data = rand(max(N));
for i = 1 : length(N); k = data(1:N(i),1:N(i)); t_sqrt(i) = timeit(@() sqrtm(k),0); t_pow(i) = timeit(@() k^(1/2), 0); end
for i = 1 : length(N); k = data(1:N(i),1:N(i)); t_sqrt1(i) = timeit(@() sqrtm(k),0); end; for i = 1 : length(N); k = data(1:N(i),1:N(i)); t_pow1(i) = timeit(@() k^(1/2),0); end
plot(N,t_sqrt,'r-',N,t_sqrt1,'r--', N,t_pow,'b-', N,t_pow1, 'b--')
legend({'sqrt, combined loop', 'sqrt, separate loops', 'pow, combined loops', 'pow, separate loop'} )
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!