How to use parfor in nested for loop?

조회 수: 2 (최근 30일)
Suraj Srivastava
Suraj Srivastava 2015년 5월 29일
편집: Greig 2015년 5월 30일
Hi, I have a nested for loop and I want to use parfor for the same, but the problem is that in my code the variable of first loop has not been used everywhere in the nested loop. And due to which it is showing error. Kindly help me out.
Thanks Suraj
  댓글 수: 2
Adam
Adam 2015년 5월 29일
You have to give more information than that, preferably including a relevant code snippet or create some test code that contains only those elements relevant to replicating the problem.
Suraj Srivastava
Suraj Srivastava 2015년 5월 29일
편집: Walter Roberson 2015년 5월 29일
a = magic(3);
for i = 1:4
for j = 2:3
a(j,2) = 4;
end
end
....................then it works for for loop. BUt when I use it in following code:-
a = magic(3);
parfor i = 1:4
for j = 2:3
a(j,2) = 4;
end
end
then it gives error.
but unfortunately I want to use this parfor in same manner. Kindly suggest me for the same.

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

답변 (1개)

Greig
Greig 2015년 5월 29일
편집: Greig 2015년 5월 30일
A couple of things to point out.
It is always best not to use i and j to index loops, these are both reserved for imaginary numbers.
The example you have given us is trivial and can be done without any loop at all - the loop over i isn't even used. For the point below, it would be really useful to know the details of what you are trying to implement. That way you will get the best possible answer.
What you will need to do is use a temporary variable in the j-loop. This will then assigned to your primary variable indexed in the i-loop. For example....
My_Output = NaN(20,10); % pre-allocate for speed
parfor ii = 1:10
Temporary_Var = NaN(20,1); % pre-allocate for speed
for jj = 1:20
Temporary_Var(jj) = some_function();
end
My_Output(:,ii) = Temporary_Var;
end

카테고리

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