matlabfor-looptime-complexityvectorizationsimplify

How to simplify my double loops by matlab vectorization?


My code is :

N = 500;  % 
D_1=ones(N,N);%
D_2=ones(N,N);% For simplicity.
B=zeros(N,N);
for i = 1:N
    for j = i+1:N
        basis_vector = zeros(N, 1);
        basis_vector(i) = 1;
        basis_vector(j) = -1;
        if D_2(i,j)>0
            w = D_1(i,j) / D_2(i,j);
        else
            w = 0;
        end
        B = B + w .* basis_vector * basis_vector';
    end
end

How to simplify my code?

Because N is too large, my code costs much time to finish。


Solution

  • Here is a vectorized version:

    w = D_1 ./ D_2;
    w(D_2 <= 0) = 0;
    m = triu(w, 1);
    d = sum(m, 1).' + sum(m, 2);
    B = -(m.' + m);
    B(1:N+1:N*N) = d;