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

2 Ansichten (letzte 30 Tage)
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

Antworten (1)

Torsten
Torsten am 26 Mai 2022
Bearbeitet: Torsten am 26 Mai 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

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by