我将假设您不会做像平方运算这样简单的事情,并且您尝试做的事情还没有在 MATLAB 中矢量化。
最好调用一次函数,在函数中做循环。随着元素数量的增加,您会注意到操作时间显着增加。
让我们的功能是:
function result = getSquare(x)
result = x*x; % I did not use .* on purpose
end
function result = getSquareVec(x)
result = zeros(1,numel(x));
for idx = 1:numel(x)
result(:,idx) = x(idx)*x(idx);
end
end
让我们从脚本中调用它们:
y = 1:10000;
tic;
for idx = 1:numel(y)
res = getSquare(y(idx));
end
toc
tic;
res = getSquareVec(y);
toc
我运行了几次代码,结果发现只调用一次函数至少快两倍。
Elapsed time is 0.020524 seconds.
Elapsed time is 0.008560 seconds.
Elapsed time is 0.019019 seconds.
Elapsed time is 0.007661 seconds.
Elapsed time is 0.022532 seconds.
Elapsed time is 0.006731 seconds.
Elapsed time is 0.023051 seconds.
Elapsed time is 0.005951 seconds.