Search code examples
performancematlaboptimizationvectorization

Is there any way that I can vectorize this code in matlab to get boost of calculations?


How to vectorize such a code in matlab? Is it possible to avoid one of the loop because calculations take long time? delta_E is a LxL matrix, alpha_i is a Lx1 matrix, i_beta is a 1xL matrix, and V is a LxL matrix. Can I please for detailed explanation?

test=input('Write: ');
pom=num2cell(test);
[L,nr_beta, step,W]=deal(pom{:});
L
nr_beta
step
W
R= -1+rand(1,L).*2;
x=[10^-2 10^4];
t=logspace(log10(x(1)),log10(x(end)),100).';
num=numel(t);
real_r2=zeros(numel(t),1);
H=diag(-1*ones(1, L-1),1) + diag(-1*ones(1, L-1),-1)+diag(R.*(W*0.5));
[V, H_eig]=eig(H,'nobalance');

E=diag(H_eig);

I am most interested in this part of code:

i=pos;
n_j=zeros(num,L);
alpha_i = V(i, :).';
i_beta = V(i, :);
delta_E = E - E.';
multi_i=alpha_i .* i_beta;
delete(gcp('nocreate'));
parpool('Threads');
parfor j=1:L
    multi=multi_i.*V(j, :) .*V(j, :).';
    for b=1:num
        n_j(b, j) = sum(exp(-1i.* t(b).* delta_E) .* multi, 'all');
    end   
end

I tried bsxfun function but I had some problems with sizes of matrix. I am also using parfor loop on the loop with b as a iterator.


Solution

  • Here is a faster version:

    for j=1:L
        vec = i_beta .* V(j, :);
        for b=1:num
            ex = exp(-1i .* t(b) .* E);
            n_j(b, j) = (vec * ex) .* (vec * (1 ./ ex));
        end
    end
    

    That is based on the following points:

    • Having vectors a,b, the expression (a .* a.') .* (b .* b.') can be written as (a .* b) .* (a.' * b.').
    • Having vectors a,b, the expression sum(a .* b.' ,'all') can written as sum (a) .* sum (b).
    • The expression out = exp(E - E.') can be written as ex = exp(E); out = ex ./ ex.'.