Search code examples
matlabfor-loopsubmatrix

matlab submatrices in loop


I have a 118800x6 matrix. the first column contains values from 1 to 99 (there are 1200 rows for each value). now I need to create a new matrix that contains 900 random rows (all of the previous column; the rows are extracted from the original matrix) for each 99 values. I tried with a for loop but that means that I have to write 99 rows of code...there is a faster way? Thank you in advance.


Solution

  • assuming your matrix is called M:

    for num = 1:99
        %Extract only rows that have the correct number in column one
        subsample = M(M(1, :) == num, :);
        %Randomly change the order of the rows of this subsample
        shuffledsubsample = subsample(randperm(1200), :);
        %Only keep the first 900 rows
        final(:,:,num) = shuffledsubsample(1:900, :);
    end