洛伦(Matlab)的艺术

将想法变成MATLAB

笔记

洛伦(Matlab)的艺术has been retired and will not be updated.

比较repmat和bsxfun性能

I've been asked repeatedly about the performance comparison between two MATLAB functions,BSXFUNrepmat。这两个函数各自都可以帮助计算两个阵列具有相同维度的计算,但是某些输入维度(而不是同意)可能具有1.。矩阵。

内容

Setup

First I set up the data.

M = 1E5;n = 100;a = rand(m,n);

Code I'm Tempted to Write

一种nd now here's the code I'm tempted to write, safely tucked inside the confines of a尝试statement.

尝试一种ZeroMean = A - mean(A);catchME disp(ME.message);结尾
Matrix dimensions must agree.

一种s you can see, MATLAB does not allow binary operators to work on arrays with different sizes (except when one of the inputs is a scalar value). There are at least two ways to remedy this.

  • Store the intermediate calculation frommean(A)in a vector and then create a new array the same size as一种与从mean。你可以做到这一点repmat或通过将适当的次数索引到该向量的行中。
  • CallBSXFUN使用适当的两个输入,并允许其执行等效的单例维度扩展。关于这一点的好处是,不需要一个大的中间阵列与一种。一种possible downside, especially sinceBSXFUNis relatively new, is that the code doesn't, at first reading, appear as obvious.
  • 定时率

    Using the most excellenttimeitutility that Steve Eddins posted to the file exchange, I now time therepmatcalculations. First I create an anonymous function that does my calculation. Then I pass that function handle totimeittimeit通过足够的运行来仔细地加热功能,以使时代不受首次效果的影响,从而弄清楚有多少次能够获得有意义的结果,等等。

    frepmat = @()a -repmat(平均(a),size(a,1),1);TimeIt(frepmat)
    ANS = 0.30964

    Indexing with ones

    repmat使用多种技术来复制一个基于“增大化现实”技术ray, depending on the details of what's being replicated. One technique is to index into the array with ones in the dimension to replicate. Here's an illustative example with a vector.

    q = [17 pi 42 exp(1)]; q5 = repmat(q,5,1)
    Q5 = 17 3.1416 42 2.7183 17 3.1416 42 2.7183 17 3.1416 42 2.7183 17 3.1416 42 2.7183 17 3.1416 42 2.7183

    定时索引

    One thing I notice with therepmatsolution is that I need to create the vectormean(A)对于功能。我需要在没有的情况下做同样的事情repmat我希望能够设置一个函数来执行计算,以便我可以使用timeit。由于我不能不将输出分配给变量,因此无法索引函数的结果,因此我创建一个中间函数卑鄙的人帮助。

    type卑鄙的人
    函数y =均值(a)mn =平均值(a);y = a -mn(一个(1,size(a,1)),:);

    现在,我准备好做时机了。

    findex = @()eyones(a);TimeIt(findex)
    ans = 0.31389

    Timing bsxfun

    接下来查看使用的时序计算BSXFUN

    fbsxfun = @() bsxfun(@minus,A,mean(A)); timeit(fbsxfun)
    ANS = 0.20569

    Punchline

    In this example,BSXFUN表现最快。现在你看到了BSXFUN在行动中,您能想到工作中此功能的用途吗?让我知道here




    以MATLAB®7.6出版

    |