在matlab中的parfor循环中调用一个函数
Call a function in parfor loop in matlab
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
其中wph1(k1,k2)为自定义函数,用于计算声子能量。但是当我尝试 运行 这段代码时,我遇到了一个错误:
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'."
如何解决这个问题?请帮忙
你只是遇到了小错误而不是 pk1
和 pk2
写 p*k1
和 p*k2
。
此外,在 matlab 中你已经定义了 pi
所以你的代码应该是
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
其他重要说明,对于这种情况,请使用 'for' 而不是 'parfor',除非每个函数调用都需要超过半秒才能到达 运行,否则您的代码将 运行 较慢,仅设置和调用 parfor 需要 10-50 毫秒。
现在是魔术。在 matlab 中,这种计算根本不需要循环,所以最快的代码是:
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
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
其中wph1(k1,k2)为自定义函数,用于计算声子能量。但是当我尝试 运行 这段代码时,我遇到了一个错误:
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'."
如何解决这个问题?请帮忙
你只是遇到了小错误而不是 pk1
和 pk2
写 p*k1
和 p*k2
。
此外,在 matlab 中你已经定义了 pi
所以你的代码应该是
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
其他重要说明,对于这种情况,请使用 'for' 而不是 'parfor',除非每个函数调用都需要超过半秒才能到达 运行,否则您的代码将 运行 较慢,仅设置和调用 parfor 需要 10-50 毫秒。
现在是魔术。在 matlab 中,这种计算根本不需要循环,所以最快的代码是:
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