i need to degenerate a matrix. I have 1 column with 11,2,2,2,3​,3..748,74​9,749 ( max 5 repetitions for each integer, but random, 2340 in total), I need to select the data in the rows with the same integer value and pick one at random to give 749 rows

i need to degenerate a matrix. I have 1 column with 1,1,2,2,2,3,3..748,749,749 ( max 5 repetitions for each integer, but random, 2340 in total), I need to select the data in the rows with the same integer value and pick one at random to give 749 rows

More Answers (1)

Try this:
% Fake data:
A(:,2) = 0:9; % fake data from 0 to 9
A(:,1) = [1,1,1,2,2,2,2,3,3,3]; % group indices
%
N = max(A(:,1));
for k = N:-1:1 % backwards is intentional!
idx = find(A(:,1)==k);
B(k,:) = A(idx(randi(numel(idx),1)),:);
end
And we can check the output in the command window:
>> A
A =
1 0
1 1
1 2
2 3
2 4
2 5
2 6
3 7
3 8
3 9
>> B
B =
1 2
2 3
3 9
The rows in B are randomly selected from A, one for each group identified by the first column. Also note looping backwards is intentional, to preallocate the array B, and that using a loop is faster than using arrayfun or cellfun.
When I run the script a few times I get these outputs:
B =
1 2
2 4
3 9
B =
1 1
2 4
3 9
B =
1 1
2 3
3 7
B =
1 0
2 6
3 9

Categories

Tags

No tags entered yet.

Community Treasure Hunt

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

Start Hunting!