How to call a function in a nested parfor loop?
조회 수: 13 (최근 30일)
이전 댓글 표시
I would like to call a bivariate function within a parfor loop, for instance the following code defines a scaler function in two variables
function f = f(x,y)
f = sin(x*y)+x^3*y^2;
Then would call the above function in a nested parfor loop, suppose I had already generated a 2D mesh grid [xx,yy] with length(xx)=m, length(yy)=n, consider following nested parfor loop:
output = zeros(m,n);
parfor i=1:m
for j = 1:n
x = xx(i,j); y = yy(i,j);
output(i,j) = f(x,y)^5+f(x,y)^7
end
end
%%%%%%%%
But the code does not generate any output, somehow it did not call 'f' at all and the output array stays to be zeros(m,n) after the loop. In an older version of the MATLAB it even generated an error saying " the left-hand side is of size 1 by 1 but the right-hand side is of size 0 by 0, which does not match", I think that indicates the 'f(x,y)' was not even passed into the nested parfor loop thus the output(i,j) was not assigned to any value at all.
Finally, I made the loop work only after I explicitly defined output(i,j) directly [i.e. output(i,j) =(sin(x*y)+x^3*y^2)^5+( sin(x*y)+x^3*y^2)^7;] . Is there any restriction in nested parfor loops that restricts multivariate function handles to be called?
By the way, I have no problem calling functions in usual nested for loops (ones without "parfor"): if I replace that "parfor" by "for" in above code, it would call 'f' perfectly fine.
(PS. In my actual coding the definition of 'f' is extraordinarily long, which motivated me to define a function handle to save some space in the main code. It would be really convenient for me if there is a way to call that function within a nested parfor loop. I am using MATLAB 2018b)
댓글 수: 0
채택된 답변
Walter Roberson
2021년 4월 20일
m = 5; n = 7;
xx = randn(m,n);
yy = randn(m,n);
output = zeros(m,n);
parfor i=1:m
xi = xx(i,:);
yi = yy(i,:);
outputj = zeros(1,n);
for j = 1:n
x = xi(j); y = yi(j);
outputj(j) = f(x,y)^5+f(x,y)^7;
end
output(i,:) = outputj;
end
imagesc(output);
%%%%%%%%
function f = f(x,y)
f = sin(x*y)+x^3*y^2;
end
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Parallel for-Loops (parfor)에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!