# How can I examine the Runtime of a preallocated loop vs non preallocated?

1 view (last 30 days)
Answered: Swetha Polemoni on 30 Mar 2021
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
in the end it should look like this :)

Swetha Polemoni on 30 Mar 2021
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
tic and toc are used to calculate the execution time. Similarly you can try for standard deviation.