MATLAB中的Metropolis算法 - >>函数句柄错误

时间:2011-02-22 15:49:10

标签: matlab

我有一块大都市算法:

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<pmetro(i,j)
                    mlat(i,j)=-mlat(i,j);
                end

            end
        end
    end
    magnet(:,ii)=sum(mlat(:))./L2;
    %figure(ii);
    %pcolor(mlat);
   % shading interp;
end


m1=mean(magnet)
error=std(magnet) ./sqrt(numel(magnet))
fprintf('Temperature = %d K',T)

figure(13)
plot(magnet(1,:),'b.')
axis([0 10 0 0.5])
grid on
xlabel('i (Configuration) ')
ylabel('M/(N*mB)')

现在,问题出在图(13)中。它给出的值大约为零(0.05,0.02 ..)。它假设给我的值大约为0.3 .. 一般来说,图表确定,它给了我正确的“形状”(它有点),但正如我所说的零。 我真的不知道怎么把这个帖子以便理解。也许我在“磁铁”矩阵中有一些错误,我不知道。 无论如何,我没有要求任何人彻底检查,我只是想问一下,如果能快速看一下,任何人都可以提供帮助。

ΕDIT---&GT;&GT;此外,有时当我运行程序时,它会给我:

  

未定义的功能或方法'mlat'   对于'double'类型的输入参数。

     

==&gt;中的错误@(I,J)(2 * MB * H)。* MLAT(I,J)

     

==&gt;中的错误   @(I,J)EXP(-de(I,J)./(KB * T))

     

==&gt;中的错误39号大都市                    如果pmetro(i,j)&gt; = 1

修改---&GT;&GT;&GT;我找到了“错误”。在循环中的代码中,我有“pmetro”函数,我将其替换为“exp( - (2 * mB * H)。* mlat(i,j)./(kB * T))“和程序工作得很好!!! 为什么它不能调用“pmetro”?我怎样才能克服这个问题?循环中的函数句柄有问题吗?

  

块引用

1 个答案:

答案 0 :(得分:3)

我非常强烈建议您在不使用任何函数句柄的情况下尝试编写代码,直到您真正熟悉Matlab为止。

这条线 de =@ (i,j) (2*mB*H).*mlat(i,j); 是什么导致你的问题。在Matlab中,当您定义一个引用数组的函数句柄时,函数句柄将使用定义时的数组。换句话说,即使mlat在循环内发生变化,函数mlat(i,j)内的de也始终相同。实际上,除非您之前在工作区中定义了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可以取平均值。无需求和,然后除以元素的数量。

相关问题