"growth" (addition) of a sequence object

In Matlab, this type of algorithm ("growing arrays") is recommended against

mine = []
for i=1:100,
    mine = [mine,randn(1)]
end

whereas it seems like many Python examples show such an algorithm (this is a really bad example):

import numpy.random as rand

mine = []
for i in range(100):
    mine.append(rand.random(1)[0])

I wonder why this is - what is the difference?

+5
source share
4 answers

The difference is that:

  • In MATLAB, each iteration of your loop redistributes the matrix to increase the size by one and copies all the contents into the newly allocated space.
  • Python . , , , , .

, , :

  • MATLAB , ( /) .
  • , Python ( ) : . Python ndarray, ndarray , MATLAB.
+7

Matlab, -, ( ), python . O (1) , - โ€‹โ€‹ , ( O (n)). , , ( O (1) ). , Matlab, , , .

python collection.deque , ( O ( 1) ).

+4

. Matlab , , Python , . Python Matlab, :

mine = mine + [newitem]

, . .append() ( .extend()).

, , Pythonistas , ``.join() .

, Python , .

+2

MATLAB . :

%# preallocation
tic
x = zeros(1,100000); for i=1:100000, x(i) = 99; end
toc

%# appending
tic
x = []; for i=1:100000, x(end+1) = 99; end
toc

%# concatenation
tic
x = []; for i=1:100000, x = [x, 99]; end
toc

:

Elapsed time is  0.001844 seconds.    %# preallocated vector/matrix
Elapsed time is  0.109597 seconds.    %# appending using "end+1" syntax
Elapsed time is 35.226361 seconds.    %# appending using concatenation

, R2011b, ( ).

, , ( , / )

, , Python . , . :

>>> from timeit import timeit

>>> timeit('x.insert(0,99)', 'x=[]', number=100000)
5.3840245059078597

>>> timeit('x.append(99)', 'x=[]', number=100000)    # x.insert(len(x),99)
0.039047700196533697
+2

All Articles