MATLAB - 网格特定区域中随机索引的排列
MATLAB - Permutations of random indices in specific areas of a grid
我有一个问题,我在 100x100 的零网格上有 4 个对象 (1),该网格被分成 16 个 25x25 的偶数正方形。
我需要创建一个 (16^4 * 4) table,其中的条目列出了 16 个子矩阵中这 4 个对象中每一个的所有可能位置。这些对象可以位于子矩阵内的任何位置,只要它们不相互重叠即可。这显然是一个排列问题,但由于索引以及位置必须是随机但在第 16 个方格内不重叠的事实,增加了复杂性。希望得到任何指点!
我试图做的是创建一个名为 "top_left_corner(position)" 的函数,该函数 returns 您所在的子矩阵左上角的下标。例如top_left_corner(1) = (1,1), top_left_corner(2) = (26,1), 等等 然后我有:
pos = randsample(24,2);
I = pos(1)+top_left_corner(position,1);
J = pos(2)+top_left_corner(position,2);
问题是如何在 table 中生成和存储 this 的排列作为线性索引。
首先使用ndgrid
以[4 , 16^4]
矩阵形式生成的笛卡尔积perm
。然后在 while 循环中生成随机数并添加到 perm 中。如果 perm 的任何列包含重复的随机数,则对这些列重复随机数生成,直到没有列重复 elements.Normally 不需要超过 2-3 次迭代。由于[100 ,100] 数组分为16 个块,使用kron
索引模式生成16 个块,并用sort
函数提取已排序元素的索引。然后生成随机数形成模式的索引(16个块)。
C = cell(1,4);
[C{:}]=ndgrid(0:15,0:15,0:15,0:15);
perm = reshape([C{:}],16^4,4).';
perm_rnd = zeros(size(perm));
c = 1:size(perm,2);
while true
perm_rnd(:,c) = perm(:,c) * 625 +randi(625,4,numel(c));
[~ ,c0] = find(diff(sort(perm_rnd(:,c),1),1,1)==0);
if isempty(c0)
break;
end
%c = c(unique(c0));
c = c([true ; diff(c0)~=0]);
end
pattern = kron(reshape(1:16,4,4),ones(25));
[~,idx] = sort(pattern(:));
result = idx(perm_rnd).';
我有一个问题,我在 100x100 的零网格上有 4 个对象 (1),该网格被分成 16 个 25x25 的偶数正方形。
我试图做的是创建一个名为 "top_left_corner(position)" 的函数,该函数 returns 您所在的子矩阵左上角的下标。例如top_left_corner(1) = (1,1), top_left_corner(2) = (26,1), 等等 然后我有:
pos = randsample(24,2);
I = pos(1)+top_left_corner(position,1);
J = pos(2)+top_left_corner(position,2);
问题是如何在 table 中生成和存储 this 的排列作为线性索引。
首先使用ndgrid
以[4 , 16^4]
矩阵形式生成的笛卡尔积perm
。然后在 while 循环中生成随机数并添加到 perm 中。如果 perm 的任何列包含重复的随机数,则对这些列重复随机数生成,直到没有列重复 elements.Normally 不需要超过 2-3 次迭代。由于[100 ,100] 数组分为16 个块,使用kron
索引模式生成16 个块,并用sort
函数提取已排序元素的索引。然后生成随机数形成模式的索引(16个块)。
C = cell(1,4);
[C{:}]=ndgrid(0:15,0:15,0:15,0:15);
perm = reshape([C{:}],16^4,4).';
perm_rnd = zeros(size(perm));
c = 1:size(perm,2);
while true
perm_rnd(:,c) = perm(:,c) * 625 +randi(625,4,numel(c));
[~ ,c0] = find(diff(sort(perm_rnd(:,c),1),1,1)==0);
if isempty(c0)
break;
end
%c = c(unique(c0));
c = c([true ; diff(c0)~=0]);
end
pattern = kron(reshape(1:16,4,4),ones(25));
[~,idx] = sort(pattern(:));
result = idx(perm_rnd).';