在matlab中特别添加 [英] special add in matlab

查看:107
本文介绍了在matlab中特别添加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
如何添加行向量到矩阵乘法之类的列向量

Possible Duplicate:
How to Add a row vector to a column vector like matrix multiplication

我有一个nx1矢量和一个1xn矢量.我想以一种特殊的方式添加它们,例如以一种有效的方式(向量化)进行矩阵乘法:

I have a nx1 vector and a 1xn vector. I want to add them in a special manner like matrix multiplication in an efficient manner (vectorized):

示例:

A=[1 2 3]'

B=[4 5 6]

A \odd_add B = 
[1+4 1+5 1+6
 2+4 2+5 2+6
 3+4 3+5 3+6
]

我已经在MATLAB中使用了bsxfun,但是我认为它很慢.请帮助我...

I have used bsxfun in MATLAB, but I think it is slow. Please help me...

推荐答案

我对这里提到的不同方法进行了比较.我正在使用 TIMEIT 函数来获得可靠的估算值(请注意代码预热,多次运行的平均时间,..):

I present a comparison of the different methods mentioned here. I am using the TIMEIT function to get robust estimates (takes care of warming up the code, average timing on multiple runs, ..):

function testBSXFUN(N)
    %# data
    if nargin < 1
        N = 500;        %# N = 10, 100, 1000, 10000
    end
    A = (1:N)';
    B = (1:N);

    %# functions
    f1 = @() funcRepmat(A,B);
    f2 = @() funcTonyTrick(A,B);
    f3 = @() funcBsxfun(A,B);

    %# timeit
    t(1) = timeit( f1 );
    t(2) = timeit( f2 );
    t(3) = timeit( f3 );

    %# time results
    fprintf('N = %d\n', N);
    fprintf('REPMAT: %f, TONY_TRICK: %f, BSXFUN: %f\n', t);

    %# validation
    v{1} = f1();
    v{2} = f2();
    v{3} = f3();
    assert( isequal(v{:}) )
end

其中

function C = funcRepmat(A,B)
    N = numel(A);
    C = repmat(A,1,N) + repmat(B,N,1);
end

function C = funcTonyTrick(A,B)
    N = numel(A);
    C = A(:,ones(N,1)) + B(ones(N,1),:);
end

function C = funcBsxfun(A,B)
    C = bsxfun(@plus, A, B);
end

计时:

>> for N=[10 100 1000 5000], testBSXFUN(N); end
N = 10
REPMAT: 0.000065, TONY_TRICK: 0.000013, BSXFUN: 0.000031
N = 100
REPMAT: 0.000120, TONY_TRICK: 0.000065, BSXFUN: 0.000085
N = 1000
REPMAT: 0.032988, TONY_TRICK: 0.032947, BSXFUN: 0.010185
N = 5000
REPMAT: 0.810218, TONY_TRICK: 0.824297, BSXFUN: 0.258774

BSXFUN无疑是赢家.

BSXFUN is a clear winner.

这篇关于在matlab中特别添加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆