2 random indexing matlab matrix binary-data
我有一个矩阵,初始化如下:
stateAndAction = zeros(11, 4);
Run Code Online (Sandbox Code Playgroud)
随着时间的推移,矩阵将被更新,以便在给定的索引处将有一个.所以在任何时候我们都可以看到这样的东西
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
Run Code Online (Sandbox Code Playgroud)
如何找到一个随机的行和列?
这是我想到的功能签名:
[random_row_index, random_column_index] = findRandom(stateAndAction)
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以使用find找到非零元素的位置,选择一个随机元素并将索引转换为数组中的行/列位置:
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
Run Code Online (Sandbox Code Playgroud)