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

2 ビュー (過去 30 日間)
kurdistan mohsin
kurdistan mohsin 2022 年 5 月 26 日
編集済み: Torsten 2022 年 5 月 26 日
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 Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by