Clear Filters
Clear Filters

randomly choose an element from each row in a matrix if it was equal to one

2 views (last 30 days)
i have the below matrix and i want to choose randomly one element from each row but only for the elements values equal to one and then save it in another matrix which will have the results (each row will have only one element equal to 1 ), anyone can help?
D= 1 1 0 1 1
1 1 1 1 1
0 0 0 0 0
1 1 1 1 1
1 0 1 0 1
0 0 1 0 0
0 0 0 0 0
0 0 1 0 0
0 0 0 0 0
0 1 0 0 0

Answers (1)

Torsten
Torsten on 26 May 2022
Edited: Torsten on 26 May 2022
You mean
D= [1 1 0 1 1
1 1 1 1 1
0 0 0 0 0
1 1 1 1 1
1 0 1 0 1
0 0 1 0 0
0 0 0 0 0
0 0 1 0 0
0 0 0 0 0
0 1 0 0 0];
[N,M] = size(D);
DD = zeros(size(D));
for i = 1:N
idx = find(D(i,:)==1)
n = numel(idx);
if n ~= 0
in = randi(n);
DD(i,idx(in)) = 1.0;
end
end

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!