MATLAB: How to make it short codes

for loopmatrix array

hi all.. if i have value of each block 8×8 pixels. i'm looking for how to random each block? any idea for it? but it's not effective. here's my codes.. could you fix it?
B=imread('filename');
a = reshape(B(1:128, 1:128), 8, 16, 8, 16);
a = permute(a, [1,3,2,4]);
%example for scramble positions
a(:,:,1,1)=a(:,:,16,2);
a(:,:,1,2)=a(:,:,2,1);
a(:,:,1,3)=a(:,:,4,1);
a(:,:,1,4)=a(:,:,6,1);
a(:,:,1,5)=a(:,:,7,4);
a(:,:,1,6)=a(:,:,9,16);
a(:,:,1,7)=a(:,:,5,10);
a(:,:,1,8)=a(:,:,7,1);
a(:,:,1,9)=a(:,:,5,1);
a(:,:,1,10)=a(:,:,5,1);
a(:,:,1,11)=a(:,:,4,4);
a(:,:,1,12)=a(:,:,3,1);
a(:,:,1,13)=a(:,:,2,3);
a(:,:,1,14)=a(:,:,2,5);
a(:,:,1,15)=a(:,:,5,4);
a(:,:,1,16)=a(:,:,15,2);
a(:,:,2,1)=...
a(:,:,..,..)=...
and so on until a(:,:,16,16). so we have 256 blocks to random without any change in the value of each block.
how to scramble it? i hope it'll easier
thanks..

Best Answer

Use tricks by Peter Acklam
B = randi(300,128,128); % Let your data

b = [8 8]; % size of small block

s = size(B);
m = s./b;
B1 = permute(reshape(B,b(1),m(1),m(2),b(2)),[1 3 2 4]);
B2 = reshape(B1,[b prod(m)]);
idx3 = randperm(size(B2,3));
B3 = B2(:,:,idx3);
a = reshape(permute(reshape(B3,b(1),s(2),[]),[1 3 2]),s(1),[]);
OR with use of cell arrays
B = randi(300,128,128); % Let your data
b = [8 8]; % size of small block
m = size(B)./b;
C0 = mat2cell(B,b(1)*ones(m(1),1),b(2)*ones(m(2),1));
ii = randperm(numel(C0));
a = cell2mat(reshape(C0(ii),m));