How to select randomly among all positive value in a matrix
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
Adam
il 24 Nov 2014
Modificato: Adam
il 24 Nov 2014
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 Commenti
Più risposte (1)
Roger Stafford
il 24 Nov 2014
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 Commenti
Vedere anche
Categorie
Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!