How to call a function in a nested parfor loop?
13 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
HLEE LEE
am 20 Apr. 2021
Bearbeitet: HLEE LEE
am 21 Apr. 2021
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 Kommentare
Akzeptierte Antwort
Walter Roberson
am 20 Apr. 2021
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
1 Kommentar
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Parallel for-Loops (parfor) finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!