parfor i=1:10
k1=0.30+(0.35/20)*i
AX(i)=k1;
for j=1:10
k2=0.5+(.35/20)*j
AY(i,j)=k2;
wph(i,j)=wph1(k1,k2)
end
end
where wph1(k1,k2) is a self defined function to calculate the phonon energy. But while i tried to run this code i eneded up with an error:
Error: An UndefinedFunction error was thrown on the workers for 'wph'. This might be because the file containing 'wph' is not accessible on the workers. Use addAttachedFiles(pool, files) to specify the required files to be attached. See the documentation for 'parallel.Pool/addAttachedFiles' for more details.
Error in yorraman (line 7) parfor i=1:10
Caused by: Undefined function 'wph' for input arguments of type 'double'."
How to fix this? please help.
You just got small bug instead of pk1
and pk2
write p*k1
and p*k2
.
Moreover, in matlab you have pi
already defined so your code should be
tic
parfor i=1:10
k1=0.30+(0.35/20)*i
AX(i)=k1;
for j=1:10
k2=0.5+(.35/20)*j
AY(i,j)=k2;
wph(i,j)=wph1(k1,k2);
end
end
toc
function u = wph1(k1,k2)
u = 2*cos(2*pi*k1) + 2*cos(2*pi*k2) + 2*cos(2*pi*(k1 - k2));
end
Other important note, for this case use 'for' and not 'parfor', unless every function call take more than half second to run, otherwise your code will run slower, just the setup and call to parfor takes like 10-50ms.
And now for the magic. In matlab you dont need for loops at all for this sort of calculation, so the fastest code is:
tic
i=1:10; k1=0.30+(0.35/20)*i; AX=k1;
j=1:10; k2=0.50+(0.35/20)*j'; AY=k2;
wph=wph1(k1,k2);
toc
% bonus: plot
[X,Y] = meshgrid(AX,AY);
surf(X,Y,wph)
function u = wph1(k1,k2)
u = 2*cos(2*pi*k1) + 2*cos(2*pi*k2) + 2*cos(2*pi*(k1 - k2));
end