在 MATLAB 中获取 0 数组中随机 1 的位置
Obtaining the position of a random 1 in an array of 0's in MATLAB
我有一个初始化如下的矩阵:
stateAndAction = zeros(11, 4);
随着时间的推移,矩阵将被更新,以便在给定的索引处,将有一个。所以在任何给定时间我们都可以有这样的东西
1 1 0 1
1 0 0 0
0 1 0 0
0 0 1 0
0 1 0 0
0 0 0 1
1 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
如何找到其中包含一个的随机行和列?
这是我想到的函数签名:
[random_row_index, random_column_index] = findRandom(stateAndAction)
你可以找到非零元素的位置,select一个随机元素并将索引转换为数组中的row/column位置:
function [random_row_index, random_column_index] = findRandom(stateAndAction)
ids = find(stateAndAction==1);
random = randi([1,numel(ids)],1);
id=ids(random);
[random_row_index, random_column_index] = ind2sub(size(stateAndAction),id);
end
我有一个初始化如下的矩阵:
stateAndAction = zeros(11, 4);
随着时间的推移,矩阵将被更新,以便在给定的索引处,将有一个。所以在任何给定时间我们都可以有这样的东西
1 1 0 1
1 0 0 0
0 1 0 0
0 0 1 0
0 1 0 0
0 0 0 1
1 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
如何找到其中包含一个的随机行和列?
这是我想到的函数签名:
[random_row_index, random_column_index] = findRandom(stateAndAction)
你可以找到非零元素的位置,select一个随机元素并将索引转换为数组中的row/column位置:
function [random_row_index, random_column_index] = findRandom(stateAndAction)
ids = find(stateAndAction==1);
random = randi([1,numel(ids)],1);
id=ids(random);
[random_row_index, random_column_index] = ind2sub(size(stateAndAction),id);
end