Speed up double sum and product

3 ビュー (過去 30 日間)
Mauro Gaggero
Mauro Gaggero 2018 年 3 月 3 日
回答済み: Tony Mohan Varghese 2018 年 3 月 22 日
Dear all,
I would like to speed up the code below. It is executed thousands of times with different values for the matrix v, so it slows down my program. Basically, I have to compute the variable etaa as the sum over i of the sum over j of the product for r from 1 to N (with r different than j) of the elements of the matrix A indexed by the matrix v (below is the formula in latex):
\eta = \frac{1}{M}\frac{1}{N} \sum_{i=1}^M \sum_{j=1}^N \prod_{r=1, r\neq j}^N A(1+v(i,j),1+(v(i,r))
I have written the code in many different forms, but I am unable to speed up the overall execution. Do you have suggestion for improving execution speed? Your help is really appreciated!
Thank you in advance.
tmpsum = 0;
for i=1:M
for j=1:N
tmpprod = 1;
for r=1:N
if(r~=j)
tmpprod = tmpprod*A(1+v(i,j),1+v(i,r));
end
end
tmpsum = tmpsum + tmpprod;
end
end
etaa = tmpsum/M/N;
As an example, the code can be executed with the following initialization:
M = 500;
N = 5;
% This 7x7 matrix is fixed
A = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0; ...
1.0, 0.9, 0.8, 1.0, 1.0, 1.0, 1.0; ...
1.0, 0.8, 0.7, 1.0, 1.0, 1.0, 1.0; ...
1.0, 1.0, 1.0, 0.7, 0.6, 1.0, 1.0; ...
1.0, 1.0, 1.0, 0.6, 0.5, 1.0, 1.0; ...
1.0, 1.0, 1.0, 1.0, 1.0, 0.7, 0.6; ...
1.0, 1.0, 1.0, 1.0, 1.0, 0.6, 0.5];
% v is a matrix of indexes used to access the elements of A. Here I wrote
% ony the first 10 rows as an example.
v = zeros(M, N);
v(1:10,:) = [1, 1, 1, 1, 3; ...
1, 1, 2, 3, 0; ...
2, 2, 3, 0, 0; ...
2, 2, 3, 0, 0; ...
3, 3, 3, 3, 3; ...
3, 3, 3, 3, 3; ...
3, 4, 4, 0, 0; ...
4, 4, 0, 0, 0; ...
4, 4, 0, 0, 0; ...
4, 4, 0, 0, 0 ...
];

回答 (1 件)

Tony Mohan Varghese
Tony Mohan Varghese 2018 年 3 月 22 日
Modify the algorithm to use parfor loop. It can execute the loop iterations on parallel workers.

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by