필터 지우기
필터 지우기

Why is vertcat slowing things down?

조회 수: 8 (최근 30일)
Doron
Doron 2012년 2월 23일
편집: Matt J 2013년 10월 22일
In the code below, 10,000 repetitions takes 2 seconds... and 100,000 repetitions takes 60 seconds! (I was expecting 20 seconds or less)...
What is going on? by a process of elimination, I suspect "vertcat" is slowing things down...
(Please see how "tic toc" behaves with repetitions = 10,000 and 100,000)
Is this a known issue with vertcat? If so, what are my other options?
(Note: looping the 10,000 algorithm 10 times would be much faster... but surely there has to be a more elegant way to do 100,000 repetitions in 20 seconds)
Thanks
Doron
*********
tic
repetitions = 10000
llim = -1;
ulim = 3;
xstack = [];
xlifestack = [];
for i = 1:repetitions
x = 0;
xlife = 0;
while ulim > x && x > llim
x = x + normrnd(0,1);
xlife = xlife + 1; % "...and the walk lives one more step"
end
if x > llim
x = ulim;
else x = llim;
end
xstack = vertcat(xstack, x);
xlifestack = vertcat(xlifestack, xlife);
end
xbar = mean(xstack);
xlifebar = mean(xlifestack);
toc

채택된 답변

Honglei Chen
Honglei Chen 2012년 2월 23일
My 2 cents::
1. You may want to preallocate the memory. The in each iteration, you just put the new data into corresponding slots.
2. If your entire purpose is to compute the mean, then why not just record the sum and number of samples and update them for each iteration. These are just scalars.
  댓글 수: 8
Doron
Doron 2012년 2월 23일
right...
xstack = zeros(100000,1)
%then
for i = 1:repetitions
% x is computed by an algorithm
xstack(i) = x
end
Doron
Doron 2012년 2월 23일
Thanks Oleg and Honglei,
I went with "xstack = (repetitions, 1)"
I don't know which one to accept as the answer, so I flipped a coin...
Thank you both
Doron

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Sparse Matrices에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by