Create vector(integer) efficiently

Running Quantlab ver 4029 or later? There is a better way to get a vector of integers to use in various range loops or vector and matrix calculations. Some example code with comments below.

→ Key take-away. Do not use function index_vector() or s2v(series(…)) or the for loop for that matter. Use the built-in vector function; for index vector generation.

//generate index vector [0,1…n]
//replaces “index_vector(n)” func more efficiently
//syntax: iterator : length ; value
out vector(integer) t(integer n) = vector(i:n;i);
//generate zero_vector
out vector(integer) t0(integer n) = vector(i:n;0);
//generate one_vector
out vector(integer) t1(integer n) = vector(i:n;1);
//generate index vector starting at 1 i.e. [1,2,3,4]
out vector(integer) t2(integer n) = vector(i:n;i+1);
//generate factorial vector [n!]
out vector(integer) t3(integer n) = vector(i:n;factorial(i));

Example workspace:

create-index-vector.qlw (9.4 KB)

2 Likes

Very useful. Thx. What would be the difference “under the hood”?

Adding to this post. Using the new form of vector allocation instead of index_vector or one_vector, will depending on size etc, speed up the code with as much as a factor 4.

There are two things at play here. 1) the compiler might recognize the new type of allocation within another structure better and optimize the structure better, and 2) there is no for loops with explicit memory allocation and throught from Qlang to memory.

So if you know your are doing loops and heavy calculations. Use the new way of vector creation.