how to select random rows from a matrix?
Ältere Kommentare anzeigen
i have a matrix of size 10037 by 9.
please tell me how to select 1000 random rows from the matrix and save it as a mnew matrix in another variable.
thanks in advance.
Antworten (2)
Andrei Bobrov
am 7 Okt. 2011
m = rand(10037,9);
k = randperm(10037);
mnew = m(k(1:1000),:);
7 Kommentare
N
am 7 Okt. 2011
Andrei Bobrov
am 7 Okt. 2011
Bearbeitet: Walter Roberson
am 10 Mär. 2024
k = randperm(size(f,1));
mnew = f(k(1:1000),:);
so?
Jan
am 7 Okt. 2011
Bearbeitet: Walter Roberson
am 10 Mär. 2024
And since Matlab 2011b:
mnew = f(randperm(size(f, 1), 1000), :);
abishek dixit
am 24 Okt. 2017
what if i want to keep that matrix as well from which the rows were extracted. i mean the matrix with remaining 37 rows.
KL
am 24 Okt. 2017
Along with Andrei's code, use
mnew_rest = f(k(1001:end),:);
Jan
am 24 Okt. 2017
Or with the original order:
M = rand(10037,9);
k = randperm(10037, 1000);
Selected = M(k, :);
r = true(1,10037);
r(k) = false;
Remaining = M(r, :);
Alejandro Reyes
am 10 Mär. 2024
This works. Thank you!
Richard Willey
am 7 Okt. 2011
Statistics Toolbox includes a nice function called randsample
% Generate a matrix named foo
foo = randn(10000,2);
% draw 1000 random samples without replacement
index = randsample(1:length(foo), 1000);
bar = foo(index,:);
% draw 1000 random samples with replacement
index = randsample(1:length(foo), 1000, true);
bar = foo(index,:);
2 Kommentare
Peter Perkins
am 7 Okt. 2011
If you happen to be using R2011b, and have access to the Statistics Toolbox, you can also use the new datasample function:
m = rand(10037,9);
mnew = datasample(m,1000);
This also allows you to sample with replacement, or with weights.
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!