Labfans是一个针对大学生、工程师和科研工作者的技术社区。 论坛首页 | 联系我们(Contact Us)
MATLAB爱好者论坛-LabFans.com
返回   MATLAB爱好者论坛-LabFans.com > 其它 > 资料存档
资料存档 资料存档
回复
 
主题工具 显示模式
旧 2019-12-14, 20:13   #1
poster
高级会员
 
注册日期: 2019-11-21
帖子: 3,006
声望力: 66
poster 正向着好的方向发展
帖子 MATLAB中的Metropolis算法->>函数句柄错误

我有一个大都会算法:

mB=5.79*10^(-9); %Bohr magnetone in eV*G^-1 kB=0.86*10^(-4); %Boltzmann in eV*K^-1 %system parameters L=60; %side square grid L2=L*L; % total number grid position Tstep=5; %step in temperature change (K) Maxstep=10; %max number of steps nmcs=5; % cycle numberof Metropolis algorithm magnet=NaN(1,Maxstep);%store magnetization in "monte carlo images" of sample %Creation initial point arrangement of magnetic spins %Outer parameters H=100000; %Gauss T=20; % Kelvin %Energy alteration in spin-reverse de =@ (i,j) (2*mB*H).*mlat(i,j); %Metropolis probability pmetro=@ (i,j) exp(-de(i,j)./(kB*T)); %Creation and display of initial lattice mlat=2*round(rand(L,L))-1; mtotal=sum(mlat(:))./L2 % Alteration of system with time for ii=1:Maxstep for imc=1:nmcs for i=1:L for j=1:L if pmetro(i,j)>=1 mlat(i,j)=-mlat(i,j); elseif rand>另外,有时当我运行该程序时,它会给我:

类型为“ double”的输入参数的未定义函数或方法“ mlat”。

==> @(i,j)(2 * mB * H)。* mlat(i,j)中的错误

==> @(i,j)exp(-de(i,j)./(kB * T))中的错误

如果pmetro(i,j)> = 1,则城市==> 39时出错

编辑--- >>>我发现了“错误”。在我具有函数“ pmetro”的循环的代码中,我将其替换为“ exp(-(2 * mB * H)。* mlat(i, j)./((kB * T))”,程序运行正常!!!为什么调用“ pmetro”不起作用?我该如何克服呢?循环中的函数句柄是否存在问题?
块引用

回答:

我强烈建议您在不熟悉Matlab的情况下尝试不使用任何函数句柄来编写代码。

行de =@ (i,j) (2*mB*H).*mlat(i,j);是什么导致您的问题。在Matlab中,当您定义一个引用了数组的函数句柄时,该函数句柄将使用定义时的数组。换句话说,即使mlat在循环内发生变化,函数de内部的mlat(i,j)也始终相同。实际上,除非您先前在工作空间中定义了mlat ,否则您甚至无法运行此代码。

因此,您应该按如下方式重写主循环

for iStep = 1:maxStep for imc = 1:mcs pmetro = $some function of mlat - this can be calculated using the entire array as input %# for each element in mlat (and thus pmetro), decide whether %# you have to switch the spin switchIdx = pmetro > 1 | pmetro < rand(size(mlat)); mlat(switchIdx) = -mlat(switchIdx); end $calculate magnetization$ end 此外,请注意,有一个命令mean取平均值。无需求和,然后除以元素数。



更多&回答...
poster 当前离线   回复时引用此帖
回复


发帖规则
不可以发表新主题
不可以发表回复
不可以上传附件
不可以编辑自己的帖子

启用 BB 代码
论坛禁用 表情符号
论坛启用 [IMG] 代码
论坛启用 HTML 代码



所有时间均为北京时间。现在的时间是 23:20


Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.