How to construct a Sliced Reduction Variable in MALTAB parallel for loop

조회 수: 2 (최근 30일)
Ahmad Gad
Ahmad Gad 2017년 11월 20일
댓글: Ahmad Gad 2017년 11월 27일
Hello all, I am having a code with the following construction. In this code, I need to extract K (M x M) from the parfor as this will save much time. Currently, I am working on it using ordinary for loop.
... % code
K = zeros(M,M);
parfor i = 1:N
k = ... % k is a matrix of dimensions (m x m) created in each pafor iteration.
u = ... % u is a vector of integers (n x 1) created in each pafor iteration.
K(u,u) = K(u,u) + k; % This line returns back an error message.
end
... % code
Is there anyway to re-write the code to be accepted in parfor loop without changing the calculation methodology. In a more general form, how can I involve a sliced reduction variable (K in this case) in parfor loop?
Thanks all and best Ahmad

답변 (2개)

Jeff Miller
Jeff Miller 2017년 11월 20일
Maybe something like this?
k = cell(N,1);
u = cell(N,1);
parfor i = 1:N
k{i} = ... % k is a matrix of dimensions (m x m) created in each pafor iteration.
u{i} = ... % u is a vector of integers (n x 1) created in each pafor iteration.
end
K = zeros(M,M);
for i = 1:N
K(u{i},u{i}) = K(u{i},u{i}) + k{i};
end
  댓글 수: 1
Ahmad Gad
Ahmad Gad 2017년 11월 20일
Hi Jeff, thanks for the answer.
I already isolated them in two different loops as you said. But my question was how to combine them all in a one parallel loop.
Thanks and best Ahmad

댓글을 달려면 로그인하십시오.


Edric Ellis
Edric Ellis 2017년 11월 21일
parfor doesn't support the notion of a variable that is both sliced and reduced. You need to recast things so that you have either a pure sliced or a pure reduced output. Here's one way that you might be able to achieve that - I'm not sure if I've completely understood your example, but perhaps this should give you sufficient information to continue:
m = 4;
n = 3;
K = zeros(m, m);
parfor idx = 1:n
% build 'k' and 'u' as per the example
k = idx .* ones(m, m);
u = (1:n)';
% Build an m-by-m increment
increment = zeros(m, m);
increment(u, u) = k(u, u);
% Ensure 'K' is a pure reduction variable
K = K + increment;
end
  댓글 수: 1
Ahmad Gad
Ahmad Gad 2017년 11월 27일
Hello Edric;
I had previously implemented a similar method, but for very big matrices (such as my cases), adding matrices many times always kills MATLAB. I am trying my best to avoid your final line
K = K + increment;
From my main example, M = 300k, N = 100k, m = n = 450
Thank you!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by