Loop optimization with row-wise sum

Viewed 48

Aiming at optimizing following nested loop, the problem is how to deal with need for row-wise sum.

for i=1:N
for j=1:N
    F(i,i)=(exp(-B(j,j))) * P(i,j)+ F(i,i);
end
end

Specifically, I want to eliminate loops and it looks achievable according to this solution but the problem is how to store changing value of F in each iteration.

I come up with this idea :

for j=1:N
    F(:)=(exp(-B(j,j))) * P(:,j)+ F(:);
end

Using this solution, F will be overwritten in every iteration!! Any idea?

1 Answers

I think your code can be simplified to the code like below

F = diag(P*exp(-diag(B)));

Example

N = 3;
B = rand(N,N);
P = rand(N,N);

F = zeros(N);
for i=1:N
for j=1:N
    F(i,i)=(exp(-B(j,j))) * P(i,j)+ F(i,i);
end
end

d = isequal(F,diag(P*exp(-diag(B)))); % check if F is identical to diag(P*exp(-diag(B)))

such that

>> d
d = 1 % indicating that they are identical
Related