如何在matlab中用矩阵运算替换这个for循环

时间:2014-05-01 22:07:06

标签: matlab for-loop

我知道在Matlab中编写for循环通常效率不高。 现在我试图用更好的选项替换嵌套的for循环。 这是嵌套循环,

for i = 1: size(A,1)
   for j = 1: size(B,1)
      S(i,j, :) = c*(A(i,:)*a - B(j,:)*b);
   end
end

我应该使用什么操作? (我在考虑笛卡尔积的实现)

3 个答案:

答案 0 :(得分:6)

尝试以下

AA = permute(A * a, [1, 3, 2]);
BB = permute(B * b, [3, 1, 2]);
CC = c * bsxfun(@minus, AA, BB);

答案 1 :(得分:1)

    A=(1:20)'*ones(1,10);
    size(A)   % 20,10
    a=ones(10,1)*(1:5);
    size(a)    %10,5
    B=ones(3,1)*(1:20);
    size(B)    %3,20
    b=ones(20,1)*(1:5);
    size(b)    %20,5
    c=1;
    Aa=A*a;
    size(Aa)   %20,5
    Bb=B*b;
    size(Bb)    %3,5
    na=size(Aa,1);
    nb=size(Bb,1);
    Ia=(1:na)'* ones(1,nb);
    %Ia=1;2;3..nb;1;2;3..nb na times
    Ia=reshape(Ia,na*nb,1);
    %Ib=1;1;natimes;2;2;2 natimes...nb;nb;nb...natimes
    Ib=ones(na,1)*(1:nb);
    Ib=reshape(Ib,na*nb,1);
    S=(Aa(Ia,:)-Bb(Ib,:))*c;
    S=reshape(S,[na nb size(Aa,2)]);

答案 2 :(得分:1)

nA = size(A,1);
nB = size(B,1);
Ar = repmat(A, nB, 1); %// repeat A along rows
Br = B(ceil(1/nA:1/nA:nB), :); %// stretch B along rows
S = c*(Ar*a-Br*b); %// do the computations
S = reshape(permute(S, [1 3 2]), nA, nB, []); %// put into shape