Reputation: 55
Question title explains what I would like. For example, if there are 6 elements in a particular column, how do I randomly pick 1 element from that column. Please keep it simple if possible.
Thanks for the help.
Upvotes: 3
Views: 2647
Reputation: 21563
Here is an easy way to do it. Note that a version without loops should be more efficient.
Assuming your variable is x
loop over its n
columns:
selected = zeros(1,n);
for c = 1:n
selected(c) = x(randperm(6,1),n);
end
Upvotes: 0
Reputation: 9864
You can use randi
if your version of MATLAB is > R2008a
samples = A(sparse(randi(size(A,1),size(A,2),1), 1:size(A,2), true));
or,
[m, n] = size(A);
samples = A(sparse(randi(m,n,1), 1:n, true));
However for older versions you can replace randi
with randsample
but that requires Statistics Toolbox. Or introduce:
randi = @(imax, m, n) floor(1+rand(m,n)*imax);
Upvotes: 3
Reputation: 114786
Suppose you have a matrix A
of size m
-by-n
. You wish to pick one element from each of the n
columns at random:
>> rows = randsample( m, n ); % sample n times from integers 1:m
Now rows
has n
values, each represent a random entry at the corresponding column.
To access those values
>> sampledValues = A( sub2ind( size(A), rows, 1:n ) );
For more information see the doc on randsample
and sub2ind
.
Upvotes: 5