How to chose random row which contain non-zero element

1 回表示 (過去 30 日間)
safaa
safaa 2017 年 4 月 5 日
回答済み: Andrei Bobrov 2017 年 4 月 5 日
For example ;
A=[ 0 0 0 0 ;
0 0 0 0;
0 0 0 0;
0 0 0 8;
0 0 0 0;
0 0 8 11;
0 0 0 0;
0 0 11 14;
11 0 0 14;
0 0 0 0;
0 8 9 14;
0 9 0 0;
0 9 0 14;
8 9 11 0;
0 0 0 0;]
If all row element zero for example row 15 I want to take another row random which contain non zero element

採用された回答

Star Strider
Star Strider 2017 年 4 月 5 日
I would first find the non-zero rows, then choose randomly amongst them:
nzr = find(sum(A,2)>0); % Indices Of Non-Zero Rows
random_nz_row = nzr(randi(length(nzr), 1)) % Choose One Non-Zero Row
nz_row = A(random_nz_row,:) % Display Random Non-Zero Row

その他の回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2017 年 4 月 5 日
another variant
inz = find(any(A ~= 0,2));
out = A(inz(randperm(numel(inz),1)),:);

カテゴリ

Help Center および File ExchangeSpecial Functions についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by