How can I examine the Runtime of a preallocated loop vs non preallocated?
1 次查看(过去 30 天)
显示 更早的评论
Hey guys, i need your help.
I want to compare the runtime of pre-allocation and built-in matrix/vector operations in comparison to using loops and no pre-allocation.
% Examine the efficiency of pre-allocation and built-in matrix/vector operations
% in comparison to using loops and no pre-allocation. For this, measure the
% runtime of the calculation of mean, std, and z-scoring for a random
% matrix three times:
% 1) As a simple built-in matrix/vector multiplication
% 2) in a loop using preallocated result variables, iterating over n, but
% not increasing the size of the result variables each iteration
% 3) in a loop without preallocation
% Plot the nine values in a bar plot. Don't create new random matrices each
% iteration but use the one that is created here.
mu = 2;
SD = 3;
m = 1000;
n = 100000;
random_matrix = randn(m,n)*SD + mu;
means = mean(random_matrix);
SDs = std(random_matrix);
zscored = (random_matrix - means) ./ SDs;
The build in matrix multiplication 1) was easy, i am struggeling at 2) and 3), do you know how to do it? thanks
回答(1 个)
Swetha Polemoni
2021-3-30
Hi
It is my understanding that you want to calculate mean of a matrix without using inbuilt function.
m=10;
n=10;
x=randn(m,n)
mean=zeros(1,n)
tic
for i=1:n
interm=0;
for j=1:m
interm=x(j,i)+interm;
end
mean(1,i)=interm/m;
end
toc
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!