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

2 次查看(过去 30 天)
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

回答(1 个)

Torsten
Torsten 2022-5-26
编辑:Torsten 2022-5-26
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

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by