'Matlab-How to run multiple randi fucntions with for loop without having indicing problems. (nearest neighbor interaction problem)
I have some code where I have a random set of spin up/spin down spinors in a matrix M. I then calculate the total energy for each spin for the neighbors neighbor interactions (M_test). I then sum up the interactions to get the whole energy for the system. I need to do this for 1000 random M matrices and store it and then graph the energy versus the order (1:1000). When I set up a for loop for i=1:1000 , I get the error "Unable to perform assignment because the indices on the left side are not compatible with the size of the right side." for M(i) in line 5.
clear, clc, close all
%bounded, where edge interactions arent counted
M = randi([0, 1], 12, 12);
M(M == 0) = -1;
M(:,12)=0;
M(:,1)=0;
M(1,:)=0;
M(12,:)=0;
for x=2:11
for y=2:11
M_test(x,y)=(M(x,y)*M(x+1,y))+(M(x,y)*M(x,y+1))+(M(x,y)*M(x,y-1))+(M(x,y)*M(x-1,y));
end
end
%summation
M_rows = sum(M_test);
Energy= sum(M_rows)
Solution 1:[1]
I don't really know if I understood well the problem but I think you have to change the matrix size in order to assign the correct index. Here's my solution let me know if it's ok.
clear, clc, close all
%bounded, where edge interactions arent counted
M = randi([0, 1], 1000, 1000);
[n,m] = size(M);
M(M == 0) = -1;
M(:,m)=0;
M(:,1)=0;
M(1,:)=0;
M(n,:)=0;
for x= 2: n-1
for y=2: m-1
M_test(x,y)=(M(x,y)*M(x+1,y))+(M(x,y)*M(x,y+1))+(M(x,y)*M(x,y-1))+
(M(x,y)*M(x-1,y));
end
end
%summation
M_rows = sum(M_test);
Energy= sum(M_rows)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | KarloKalenda |
