How can I randomly select a subset of logicals?

3 次查看(过去 30 天)
Goal: I have a vector of logicals, 4203x1. These logicals correspond to trials with the conditions I want (in this example, about 48 out of 4203 are 1s, the rest are 0s). I would like to randomly downsample from these 48 to 20 to match the number of trials in another condition. How might I go about this?

采纳的回答

James Tursa
James Tursa 2020-3-31
编辑:James Tursa 2020-3-31
T = your logical trials vector
n = 20; % number of trials to keep
f = find(T); % find the location of the 1's
f = f(randperm(numel(f))); % randomize the find results
T(f(n+1:end)) = false; % get rid of the other trials beyond the random 20
Or if you need to do this repeatedly for the same T, do the f = find(T) only once, then repeatedly do this
R = T;
f = f(randperm(numel(f))); % randomize the find results
R(f(n+1:end)) = false; % get rid of the other trials beyond the random 20
Alternatively, one could start with an all 0's matrix and then repeatedly randomly fill with 1's. E.g.,
R = false(size(T));
f = f(randperm(numel(f))); % randomize the find results
R(f(1:n)) = true; % randomly fill in the 1's

更多回答(1 个)

dpb
dpb 2020-3-31
Nmatch=20; % don't bury data in code; use variables for a variable factor
isM=find(v); % population of indices that match
ix=isM(randperm(numel(isM),Nmatch); % random selection of Nmatch out of total

类别

Help CenterFile Exchange 中查找有关 MATLAB 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by