MATLAB: How Can I randomly select 20% of the array elements AND save their indices (row,column)

randomsample

I have a matrix A with n points.
A = [230,30,40,40,80;40 40 30 80 230;40 40 40 230 80]; n=numel(A);
How can i now randomly select a percentage of the points (example p=20% of n) ?
The output should be a new matrix with these random elements. AND another array that tells me "which" elements(row, column) were selected.
Any help appreciated 🙂

Best Answer

A = [230,30,40,40,80;40 40 30 80 230;40 40 40 230 80];
n = numel(A);
Index = randperm(numel(A), ceil(numel(A) * 0.20));
[Xp, Yp] = ind2sub(size(A), Index);
Selected = A(Index);
This chooses 20% of the values randomly and replies the values in Selected and the indices in Xp, Yp.