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

조회 수: 1(최근 30일)
Catayoun Lissa Eleonore Azarm 2021년 1월 30일
답변: Swetha Polemoni 2021년 3월 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표시숨기기 없음
Catayoun Lissa Eleonore Azarm 2021년 1월 30일
in the end it should look like this :)

댓글을 달려면 로그인하십시오.

### 답변(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
tic and toc are used to calculate the execution time. Similarly you can try for standard deviation.

댓글을 달려면 로그인하십시오.

### 범주

Find more on Debugging and Analysis 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!

Translated by