在 MATLAB 中,我将z
任意大小的数组作为输入。我现在希望创建一个w
具有相同维度的数组z
,但其值无处不在k
,一些实数。以下是我想到的两种方法:
z = rand(1000,1000); % pretend the size of z is not known beforehand
k = 2.3;
w = ones(size(z))*k;
w = zeros(size(z)) + k;
w = z - z + k;
我试图看看这些方法中哪一种最快,结果让我感到非常惊讶:
tic; for n = 1:1000, w = ones(size(z))*k; end; toc
tic; for n = 1:1000, w = zeros(size(z)) + k; end; toc
tic; for n = 1:1000, w = z - z + k; end; toc
Elapsed time is 7.243662 seconds.
Elapsed time is 4.770328 seconds.
Elapsed time is 2.750093 seconds.
更令人惊讶的是 for k = 1
(人们认为ones()
会是最快的)
tic; for n = 1:1000, w = ones(size(z)); end; toc
tic; for n = 1:1000, w = z - z + 1; end; toc
Elapsed time is 4.856666 seconds.
Elapsed time is 2.759324 seconds.
那么,我的问题是,我的结果是否正确?如果是这样,是w = z - z + k
初始化数组的最快方法k
,还是有更好的方法?