Problems encountered in Parallel Processing

Dear All,
I tried to use parfor to run my code which is given as follows:
function [A,B] = temp_test(x)
a = [1:2*x]; b = [1:x];
A = zeros(1,x); B = zeros(x,1);
parfor i = 1 : x
j = x + 1;
c = func1(a(j),b(i));
A(i) = c;
B(i) = a(j) + b(i);
end
function [d] = func1(e,f)
d = e*f;
end
end
But I was told I can not call func1 like this because it is a nested function. Would anybody tell me how I can fix this problem but I still want to keep the func1 as it is?
Thanks a lot.
Benson

 채택된 답변

Matt J
Matt J 2019년 8월 30일

1 개 추천

Is there any reason not to simply make func1 a local function?
function [A,B] = temp_test(x)
a = [1:2*x]; b = [1:x];
A = zeros(1,x); B = zeros(x,1);
parfor i = 1 : x
j = x + 1;
c = func1(a(j),b(i));
A(i) = c;
B(i) = a(j) + b(i);
end
end
function [d] = func1(e,f)
d = e*f;
end

댓글 수: 5

Benson Gou
Benson Gou 2019년 8월 30일
Actually func1 is a very large function. I just created a simple example to show my problem.
Thanks a lot.
Benson
Matt J
Matt J 2019년 8월 30일
편집: Matt J 2019년 8월 30일
How does the size of func1 invalidate my advice? A local function can be any size.
Benson Gou
Benson Gou 2019년 8월 30일
The function func1 has hunreds of lines. The code will becomes very hard to debug if I insert all lines of func1 in the loop of parfor. I am wondering if there is a way to solve this problem of nested function while func1 is kept the same way as it is.
Matt J
Matt J 2019년 8월 30일
편집: Matt J 2019년 8월 30일
I don't think you read my initial post carefully. If you look, you will see that I did not relocate the code of func1 inside the parfor loop. I simply made it into a local function. You could also move func1 to its own file. This might be a good idea if its code is as long and involved as you say.
Benson Gou
Benson Gou 2019년 8월 30일
Dear Matt,
I am very sorry I did not clearlly read your answer. I tried your changed code and it works very well.
Thanks a lot and have a good weekend!
Benson

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

질문:

2019년 8월 30일

댓글:

2019년 8월 30일

Community Treasure Hunt

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

Start Hunting!

Translated by