

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
The matlab code for simulating the metropolis algorithm for a 2d ising model. The algorithm is used to study the statistical mechanics of a ferromagnetic system, where each spin can be in one of two possible states. The code initializes the spins, sets the boundary conditions as periodic, and then performs the metropolis algorithm to calculate the energy of the system and determine if a spin flip should be accepted based on the metropolis criterion.
Typology: Exercises
1 / 2
This page cannot be seen from the preview
Don't miss anything!


clear all; n =3; nnn = 1; nbin = 200; T =4.; JJ = -1.0; nmc = 1000; beta = 1/T; rand('state', 0) %----------- generate random spins for the first time ---- for ip= 2: n+ for jp= 2: n+ rr = 2.rand - 1.0 ; s(ip,jp) = sign(rr); %s(ip,jp) = 1; end end s %------------- fix the boundary conditions as periodic ------ for ja=2: n+ s(1,ja) = s(n+1,ja); s(n+2,ja) = s(2, ja); end for ia=2: n+ s(ia,1)= s(ia,n+1); s(ia,n+2) = s(ia,2); end % ------------------------------------------------------------ %i = 2; j = 2; for j = 2: n+1 % loop over all mesh points for i = 2: n+1 % loop over all mesh points en_initial = JJs(i,j)(s(i+1,j)+s(i-1,j)+s(i,j+1)+s(i,j-1)); s_old = s(i,j); % save this for possible reverting if(s(i,j)== +1) snew = -1; end if(s(i,j)== -1) snew = +1; end s(i,j) = snew; %(spin flip has been done) % refresh the boundary values for the flip for jj=2: n+ s(1,jj) = s(n+1,jj); s(n+2,jj) = s(2, jj); end for ii=2: n+ s(ii,1) = s(ii,n+1); s(ii,n+2) = s(ii,2); end en_final = JJs(i,j)(s(i+1,j)+s(i-1,j)+s(i,j+1)+s(i,j-1)); delta_e = en_final - en_initial; if(delta_e<=0) s(i,j) = snew; % keep the flip 'spin is flipped; as delta_e<=0 ' end if(delta_e>0) rr = rand; if(rr<= exp(-betadelta_e)) s(i,j)= snew; % again keep the flip 'spin is flipped when delta_e>0' elseif(rr>exp(-beta*delta_e)) s(i,j) = s_old; % remove the flip 'spin is not flipped' end end % refresh the boundary values after the flip ------------- for jk=2: n+ s(1,jk) = s(n+1,jk); s(n+2,jk) = s(2, jk); end for ik=2: n+ s(ik,1) = s(ik,n+1); s(ik,n+2) = s(ik,2); end s
% end of the Matropolis algo ------------------------------ end % end of i-loop end % end of j-loop