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!