MATLAB: Swapping 2 random array elements and picking subsequent array pairs

algorithmmatrix indexingsum

I'm try to come up with code that can randomly swap 2 elements (and only 2 at a time) from an array of 27 unique numbers. For instance, a=[4 1 9 13 27 20 19 ….] would become anew=[19 1 9 13 27 20 4 ….]
I also don't know the code for picking subsequent pairs from an array and using that pair as an index of a matrix. For instance, if a=[4 1 9 13 27 20 19 ….] and M is a 27X27 matrix, I'm trying to find the sum M(4,1)+M(1,9)+M(9,13)+M(13,27)+M(27,20)+M(20,19)+…
I've been playing around with sum=sum+__ notation, but I'm a total Matlab noob 🙁

Best Answer

pair = randperm(length(a), 2);
anew = a;
anew(pair) = anew(fliplr(pair));
Msum = sum( M(sub2ind([27, 27], anew(1:end-1), anew(2:end))) );