Search code examples
matlabrandomsparse-matrixsparse-array

Sampling a matrix in Matlab


I have the sparse Matrix having 300 to 900 rows with 3 columns, I want the sampling of this matrix i.e 20 samples of Matrix of the whole Matrix. How can I sample my matrix MAT in Matlab.


Solution

  • I assume you want random sampling (without replacement); that is, you want to pick n elements out of matrix A randomly. For that you can apply randsample on the linearized, full version of A:

    result = randsample(full(A(:)), n);
    

    If you want to avoid converting A into full (for example, because of memory limitations), use

    result = A(randsample(numel(A), n)); %// result in sparse form
    

    or

    result = full(A(randsample(numel(A), n))); %// result in full form