【问题标题】:Change Random Element of a Matrix with small Restriction更改具有小限制的矩阵的随机元素
【发布时间】:2014-09-01 12:50:24
【问题描述】:

我有一个 Vector 1xm、ShortMemory (SM) 和一个 Matrix nxm、Agenda (AG)。 SM 只有正整数和零。 AG的每一列只有一个元素等于1,同一列的所有其他元素都等于0。

我的目标是从 AG 中随机选择的列中更改数字 1 的位置。问题是SM中只有对应0的列才能被改变。

例子:

SM = [1 0 2];
AG = [1 1 0 ; 0 0 1 ; 0 0 0];

这里随机生成的数字

RandomColumn = 2;

可能的结果是

AG = [1 0 0 ; 0 1 1 ; 0 0 0]; or AG = [1 0 0; 0 0 1 ; 0 1 0]; or AG = [1 1 0 ; 0 0 1 ; 0 0 0];

得到 1 的 Line 也是随机的,但这很容易做到

我可以通过获取 1 到 m 之间的随机数来做到这一点,但 m 在我的问题中可能非常大,零的数量也可能非常小,因此可能需要很长时间。我也可以用一个循环来做,但它是 Matlab 并且已经嵌入了双循环。

谢谢

编辑:为清晰起见,在代码中添加了注释。

编辑:更正了可能结果的错误

【问题讨论】:

  • 你想要达到的目标很难理解。在示例AG 中,如果SM(2) 中存在0,则更改第2 列的模式是什么?你已经给出了 2 个例子,但我不明白这个模式。
  • 为什么第二个AG的第三列有两个?
  • 模式也是随机的,在我的程序中我选择了一条随机线,将RandomColumn设置为全0,然后将该列的#randomline设置为1,该线可以与它相同是以前。每列只能有 1 个“1”,但在 AG 中每行可以有任意数量。
  • 引用:>,但第二个AG在第三列中有两个。
  • @AntonioCraveiro 我的解决方案有错误,等我编辑它。

标签: arrays matlab random vector matrix


【解决方案1】:

我的解决方案基于以下假设:

  1. 目标是从 AG 中随机选择的列中更改数字 1 的位置。
  2. 只能更改 SM 中对应 0 的列。

解决方案:

% input
SM = [1 0 2]
AG = [1 1 0 ; 0 0 1 ; 0 0 0]

% generating random column according to assumptions 1 and 2
RandomColumn1 = 1:size(AG,2);
RandomColumn1(SM~=0)=[];
RandomColumn1=RandomColumn1(randperm(length(RandomColumn1)));
RandomColumn=RandomColumn1(1);

% storing the current randomly chosen column before changing
tempColumn=AG(:,RandomColumn);

% shuffling the position of 1
AG(:,RandomColumn)=AG(randperm(size(AG,1)),RandomColumn);

% following checks if the column has remained same after shuffling. This while loop should execute (extremely) rarely.
while tempColumn==AG(:,RandomColumn)
   tempColumn=AG(:,RandomColumn);
   AG(:,RandomColumn)=AG(randperm(size(AG,1)),RandomColumn);
end
AG

【讨论】:

  • AG(:,RandomColumn)=AG(randperm(size(AG,1)),RandomColumn); 缺少 ) 和尺寸不匹配
  • 你确定吗?如果我复制粘贴,对我来说运行完美
  • 是的,我想我复制了它 b4 你编辑了 3 分钟来测试是合理的:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-27
  • 1970-01-01
  • 2018-05-23
相关资源
最近更新 更多