Generate vector with incremental values ​​in matlab

Given an integer n, I would like to get a vector as follows. For example. if n = 3, then the vector must be [1,1,2,1,2,2,3], and if n = 4, then the vector must be [1,1,2,1,2,3,1,2, 3, 4] etc. Is there an easy way to do this? Thanks.

+4
source share
3 answers

Here's a solution that uses the "upper triangular matrix" function to select the necessary entries from a simple repetition of the complete sequence:

A = triu(repmat((1 : n)', 1, n));
A = A(A ~= 0)'

triu . , , , , 1 : n. triu :

A = repmat((1 : n)', 1, n);
A = A(triu(ones(n)) ~= 0);

, 1 n = 10000 .

, , , ( 2 n/(n + 1)).

+2

,

w=ones(1,n*(n+1)/2);
w(1+cumsum(1:n-1))=-(0:n-2);
w=cumsum(w);

Dennis n<=8, .

:

n=2000;
N=1e6/n;

tic
for k=1:N
    A = repmat((1 : n)', 1, n);
    A = A(triu(ones(n)) ~= 0);
end
toc


tic
for k=1:N
    w=ones(1,n*(n+1)/2);
    w(1+cumsum(1:n-1))=-(0:n-2);
    w=cumsum(w);
end
toc

tic
for k=1:N
    %// Fast vector growing
    v=[];
    for t = 1:n
        x = 1:t;
        v(end+x) = x;
    end
end
toc 

n=4

Elapsed time is 5.688693 seconds.
Elapsed time is 3.576366 seconds.
Elapsed time is 1.878887 seconds.

n=8

Elapsed time is 2.985184 seconds.
Elapsed time is 1.851967 seconds.
Elapsed time is 1.834574 seconds.

n=100

Elapsed time is 1.084404 seconds.
Elapsed time is 0.352033 seconds.
Elapsed time is 2.502724 seconds.

n=1000

Elapsed time is 15.625361 seconds.
Elapsed time is 3.949131 seconds.
Elapsed time is 11.497764 seconds.

n=2000

Elapsed time is 29.940548 seconds.
Elapsed time is 7.649394 seconds.
Elapsed time is 22.846367 seconds.
+3

. , , @A. Donda @Mohsen, , , n = 1000 , .

The most interesting part is the difference in speed between the two methods, the second and third can also work for n=10000within a second, but the first is much slower!

n = 1000;

% Slow vector growing
tic
v=[];
for t = 1:n
   v = [v 1:t];
end
toc % 0.6 sec


tic
% Fast vector growing
v=[];
for t = 1:n
    x = 1:t;
    v(end+x) = x;
end
toc % 0.01 sec

tic
% Preallocated loop
v=zeros(n*(n+1)/2,1);
count = 0;
for t = 1:n
    x = 1:t;
    v(count+x) = x;
    count = count+t;
end
toc % 0.01 sec as well
+1
source

All Articles