Extract subsets of consecutive entries in a matrix

3 views (last 30 days)
I have an n x p matrix, A, of multivariate data. (n - data points, p - independent variables).
I want to select random subsets (i.e. extract collections of rows) from this data of size (p+1). The subsets need to be comprised of rows that are consecutive.
For example:
matrix = rand(100,4);
%n = 100, n data points
%p = 4, p independent variables
I want to create a random subset of 5 rows (p+1 = 5). So, rows 1 through 5 or 43 through 47, etc.
I know there are functions like randsample and datasample but I'm not sure how to use these to get subsets of rows that are together and not chosen at random throughout the matrix.

Accepted Answer

Walter Roberson
Walter Roberson on 26 Jan 2021
n = 100
n = 100
p = 4;
matrix = rand(n, p);
selected = select_consecutive_rows(matrix, p+1);
selected
selected = 5×4
0.9500 0.3396 0.5564 0.5069 0.4703 0.4893 0.0263 0.5017 0.7375 0.5300 0.5425 0.3738 0.8417 0.3768 0.0314 0.1109 0.0088 0.1602 0.9851 0.8399
function selected = select_consecutive_rows(matrix, p)
idx = randi(size(matrix,1)-p+1);
selected = matrix(idx:idx+p-1, :);
end

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!