Loren on the Art of MATLAB

Turn ideas into MATLAB

Note

Loren on the Art of MATLAB已退休,不会更新。

隐式膨胀性能的重要性

Sometimes people state that they like using MATLAB because it's easy to express their mathematical thoughts. Sometimes there's a follow-on that they then switch to another language for performance. While early in the history of MATLAB, that was sometimes beneficial, it is not so obvious these days. Let's take the example of隐性扩展(also这里).

To maximize the benefits of implicit expansion, it's best if you have a more complicated, computationally expensive expression for MATLAB to work with while minimizing the need for temporary arrays. MATLAB can then exploit coarse grain parallelism. But it also depends on your computer and the array sizes you are using. And it's worth thinking about code maintenance (for the future) and its complexity/simplicity.

Contents

示范

Here is demonstration of this simple idea. I'm testing equivalent numerical algorithms for removing the mean of any array and scaling it. Below are three equivalent implementations in MATLAB, the last one embeds a possible temporary array into one single line to take advantage of the most magic possible. The first one uses the well-namedbsxfun功能。第二个使用与第一个相同的步骤,但使用隐式扩展。第三种方法结合了一些步骤,因此总体语句较少。我称这个很聪明。

n = [300, 1000, 3000, 10000]; alltimes = zeros(length(n),4);%alltimes = table( "size", [length(n),4],...% "VariableNames",["n", "bsxfun", "implicit","smart"]);fori = 1:length(n) runtimes = testRemoveMeanAndScale(n(i)); alltimes(i,:) = [n(i), runtimes];end格式短的galltimest = array2table(alltimes,"VariableNames",["n","bsxfun",“隐性”,“聪明的”)))
alltimesT = 4×4 table n bsxfun implicit smart _____ __________ __________ __________ 300 0.00024632 0.00014821 7.5306e-05 1000 0.00322 0.0036559 0.0027499 3000 0.030063 0.036868 0.027908 10000 0.3469 0.38712 0.33361

想法

您可以看到时间不完全一致。似乎随着阵列变大,智能算法始终优于其他算法。隐性扩展和bsxfunare generally on par except for small matrix sizes, where perhaps the extra function call costs enough extra to be noticeable.

Which Code Do You Prefer, and Why?

我想知道您想要哪种代码,我很想听听您的理由。让我知道这里.

%% Test FunctionsfunctionRuntime = testRemoveMoveMoveMoveMoveMoveMeanandScale(n)%此功能测试我们希望比较W.R.T.的3种算法。速度。RNG(0);x = rand(n);mu = rand(1,n);sigma = randi([0 1],1,n);运行时(1)= timeit(@()bsxfunremovemeanandscale(x,mu,sigma));运行时(2)= timeIt(@()inditexpansionRemoveMeanandScale(x,mu,sigma));运行时(3)= timeit(@()smartremovemeanandscale(x,mu,sigma));end% testRemoveMeanAndScalefunctionX = bsxfunRemoveMeanAndScale(X, mu, sigma)% Implementation using bsxfunx = bsxfun(@minus,x,mu);Sigma(Sigma == 0)= 1;x = bsxfun(@rdivide,x,sigma);end% bsxfunRemoveMeanAndScalefunctionX =含义XpansionRemoveMeanandScale(X,MU,Sigma)% Use implicit expansionx = x -mu;Sigma(Sigma == 0)= 1;x = x ./ sigma;end%rectitexpansionRemoveMeanandScalefunctionX = SmartremoveMeanandScale(X,MU,Sigma)%建议隐性扩展实施Sigma(Sigma == 0)= 1;x =(x -mu)./ sigma;end%smartremovemeanandscale




Published with MATLAB® R2019b

|