Vector initialization (randn) with loop 'for'

1 visualización (últimos 30 días)
Viacheslav Klimentyev
Viacheslav Klimentyev el 13 de En. de 2015
Comentada: Viacheslav Klimentyev el 13 de En. de 2015
I am initializing vector by randn function (two ways).
1.
clc
clear all
N = 1e6;
x = zeros(N, 1);
tic
for k = 1 : N
x(k) = randn;
end
toc
Elapsed time is 0.054535 seconds.
2.
clc
clear all
N = 1e6;
x = zeros(N, 1);
tic
for k = 1 : N
x(k) = randn(1,1);
end
toc
Elapsed time is 1.491623 seconds.
In both cases function randn returns one element (array 1x1), but elapsed time differs by ~30 times. Why?

Respuestas (1)

Iain
Iain el 13 de En. de 2015
The time difference is due to what gets done in the loop.
randn - This checks the number of inputs (0), generates a number and spits it out.
randn(x,y) - This checks the number of inputs (2), checks to see if it includes instructions to reset the seed, checks to see if they're actual valid numbers, etc., then goes about generating a number to spit it out.

Categorías

Más información sobre Logical en Help Center y File Exchange.

Productos

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by