How to select randomly among all positive value in a matrix
Ältere Kommentare anzeigen
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
Akzeptierte Antwort
Weitere Antworten (1)
Roger Stafford
am 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.
Kategorien
Mehr zu Creating and Concatenating Matrices finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!