How to select randomly among all positive value in a matrix

9 ビュー (過去 30 日間)
Moe
Moe 2014 年 11 月 24 日
回答済み: Roger Stafford 2014 年 11 月 24 日
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

採用された回答

Adam
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.

その他の回答 (1 件)

Roger Stafford
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.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by