Preallocating memory in MATLAB à la std :: vector :: reserve (n)

So, it is reservevery useful if you have an approximate idea of ​​your size requirements. Does anyone know of a similar method for pre-distributing arrays in MATLAB?

I don't really like hacker (but effective) methods, such as:

x = zeros(1000,1);
for i = 1:10000
    if i > numel(x)
       x = [x;zeros(size(x))];
    end
    x(i) = rand;
end
x(i+1:end) = [];
+5
source share
3 answers

The "hacker" way is the only way to do this. However, you do not need to check i <= numel (x). The array will be expanded automatically (but without doubling the array):

x = zeros(1000,1);
for i = 1:10000
    x(i) = rand;
end
x(i+1:end) = [];

EDIT: To keep it simple while maintaining array doubling, you can write a class or just a few helper functions (below).

EDIT2: . MATLAB 2010 , . MATLAB 2011 , , . , , . .

function listtest()
    n = 10000;
    l = new_list();
    for i=1:n
        l = list_append(l, i);
    end
    a = list_to_array(l);
end

function l = new_list()
    l = [0 0];
end
function l = list_append(l, e)
    if l(1)+1 == length(l)
        l(length(l)*2) = 0;
    end
    l(1) = l(1)+1;
    l(l(1)+1) = e;
end
function a = list_to_array(l)
    a = l(2:1+l(1));
end

EDIT ( AndrewJanke)

.

function manual_reserve_example(n)
x = zeros(1000,1);
for i = 1:n
    if i > numel(x)
       x = [x;zeros(size(x))];
    end
    x(i) = i;
end
x(i+1:end) = [];
end

function naive_growth(n)
x = 0;
for i = 1:n
    x(i) = i;
end
end

function compare_them(n)
fprintf('Doing %d elements in Matlab R%s\n', n, version('-release'));
tic;
naive_growth(n);
fprintf('%30s  %.6f sec\n', 'naive_growth', toc);
tic;
manual_reserve_example(n);
fprintf('%30s  %.6f sec\n', 'manual_reserve', toc);
tic;
listtest(n);
fprintf('%30s  %.6f sec\n', 'listtest', toc);
end
+3

, , - .

for i = 10000:-1:1
    x(i) = rand;
end

, , , .


"double on overflow", .

, Matlab , . , , . ( , -.)

+1

MATLAB 7.6 (R2008a) STRUCT REPMAT.

1:

s.field1 s.field2

s = struct('field1',cell(1),'field2',cell(1));

2:

s.field1.subfield

s = struct('field1',struct('subfield',cell(1)));

3:

V (1).field1 ... v (100).field1

s = struct('field1',cell(1));
v = repmat(s,100,1);
0

All Articles