Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create large random vectors efficiently, without resorting to loops?

Tags:

matlab

Problem statement:- I want to create 50 instances of a vector(1 Dimension) which contains random real numbers(float). The array size(1 dimension) will be say 30 thousand.How do i proceed so that the overhead is minimum or complexity is minimum?

like image 976
SKM Avatar asked Jul 06 '10 12:07

SKM


2 Answers

N = 30000; %// length of your vectors
I = 50; %// number of instances
v = rand(I, N); 

In the example above you will generate a matrix, in which every row is a single vector. Random numbers are generated with uniform distribution (for Gaussian distribution, use randn).

If you need to create every instance separately use a loop:

for i=1:I
    v = rand(1, N);
    %// do something with v
end

But I wouldn't use that if I were you (it is slower and IMHO less clear).

EDIT:
Regarding your question under Mau's answer:
No, you don't need to index it on your own. Let Matlab do it for you.
For example, if you need to repeat following operation 50 times:

 x1 = sigma*y + beta * vect1;
 ...
 x50 = sigma*y + beta * vect50;

assuming y is a vector of size 1x30000, you can compute it in one line:

X = sigma*repmat(y, 50, 1) + beta * rand(50, 30000);

explanation: every row is a single vector you wanted to compute:

X(1,:) = x1;
...
X(50,:) = x50;

repmat(y,50,1) repeats your y vector 50 times in first dimension (rows)

like image 163
Gacek Avatar answered Sep 26 '22 23:09

Gacek


Create a 50x30k matrix of random values

values = rand(50, 30000)

then each row will be a 30k-values random vector

 aVector = values(3,:)  % Row 3, all columns
like image 44
Mau Avatar answered Sep 23 '22 23:09

Mau