How to randomly generate one non-zero element of each row from a matrix

9 ビュー (過去 30 日間)
Chaoyang Jiang
Chaoyang Jiang 2018 年 7 月 3 日
編集済み: Stephen23 2018 年 7 月 3 日
How to randomly generate one non-zero element of each row from a matrix and then create a new matrix?
For A=[1 5 6 7 0; 2 0 0 4 2; 0 0 3 4 0]; I want to have a random vector B where each element in B (non-zero) is randomly generated from A. e.g., B=[1,2,3] or [5 4 3] or [7 2 3]...

回答 (2 件)

Rik
Rik 2018 年 7 月 3 日
There's probably a faster way, but the code below should work.
A=[1 5 6 7 0; 2 0 0 4 2; 0 0 3 4 0];
A_cell=cellfun(@(x) x(x~=0),...
mat2cell(A,ones(1,size(A,1)),size(A,2)),...
'UniformOutput',false);
B=arrayfun(@(x) x{1}(randi(numel(x{1}))),A_cell);
  4 件のコメント
Stephen23
Stephen23 2018 年 7 月 3 日
"This line might in a loop that will be repeated 10,000 times. I am hoping there will be an efficient way."
@Chaoyang Jiang: why not just generate all random selection at once? Is a loop strictly required?
Chaoyang Jiang
Chaoyang Jiang 2018 年 7 月 3 日
Yes, as each loop is independent and has totally different A.

サインインしてコメントする。


Stephen23
Stephen23 2018 年 7 月 3 日
編集済み: Stephen23 2018 年 7 月 3 日
In two lines:
>> A = [1,5,6,7,0;2,0,0,4,2;0,0,3,4,0];
>> [R,C] = find(A);
>> accumarray(R,A(A~=0),[],@(v)v(randi(numel(v))))
ans =
5
2
3
>> accumarray(R,A(A~=0),[],@(v)v(randi(numel(v))))
ans =
7
2
3
>> accumarray(R,A(A~=0),[],@(v)v(randi(numel(v))))
ans =
5
2
3
>> accumarray(R,A(A~=0),[],@(v)v(randi(numel(v))))
ans =
6
4
3
>> accumarray(R,A(A~=0),[],@(v)v(randi(numel(v))))
ans =
7
2
3
>> accumarray(R,A(A~=0),[],@(v)v(randi(numel(v))))
ans =
6
2
4
>> accumarray(R,A(A~=0),[],@(v)v(randi(numel(v))))
ans =
5
2
3
Or slightly more clearly:
[R,~] = find(A);
fun = @(v)v(randi(numel(v)));
B = accumarray(R,A(A~=0),[],fun)

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by