How to select randomly among all positive value in a matrix
2 次查看(过去 30 天)
显示 更早的评论
Hi everyone,
I need a fast and efficient code for the following problem:
Suppose I have matrix m and m2m:
m = [3;4;5;-1;2;-4];
m2m2 = [-2;-5;-6;-3;-8;-1];
I need to find all positive value in matrix m or in matrix m2m, and then, select randomly one value among of them. Note that, matrix m and m2m can't be positive at the same time.
This random selection is index of matrix array. For example, if array 4 is randomly selected in matrix m, then I need results to be 2 (2 means second array(index)).
% If rm = find(m(j)>0)
% select random one array
% elseif rm2m = find(m2m(j)>0)
% select random one array
0 个评论
采纳的回答
Adam
2014-11-24
编辑:Adam
2014-11-24
idx = find( m > 0 );
if isempty( idx )
idx = find( m2m2 > 0 );
if isempty( idx )
% Throw an appropriate wobbler
end
end
chosenIdx = idx( randi( numel(idx) ) );
You need to do something in there to tell you whether that is an index into matrix m or matrix m2m2, but that is trivial.
0 个评论
更多回答(1 个)
Roger Stafford
2014-11-24
If I understand you correctly, do this:
f = find([m;m2m]>0); % Find all positive value in either array
i1 = f(randi(numel(f))); % Choose one of them randomly
i2 = (i1>numel(m))+1; % i2 is 1 if choice is in m and 2 if choice is in m2m
i1 = i1-(i2>1)*numel(m); % Adjust i1 to be index relative to m2m if choice is there
The index 'i2' will be 1 if the randomly selected positive value is in 'm' and 2 if in 'm2m'. The index 'i1' will be the index within 'm' or 'm2m' whichever contains the selection.
Note that the random choice will be uniformly distributed among all positive values in the two arrays.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!