generate random numbers among each non zero column elements

5 ビュー (過去 30 日間)
Chaoyang Jiang
Chaoyang Jiang 2018 年 4 月 18 日
コメント済み: Chaoyang Jiang 2018 年 5 月 3 日
Given a=[0 1 1; 1 1 1; 1 0 1], the row index of first elements of 1st colomn is [2 3], 2nd colomn is [1 2] and 3rd colomn is [1 2 3].
Then I want to generate random numbers among each row index, e.g.:
generate 1 random number from 1st column index [2 3],
generate 1 random number from 2nd column [1 2],
generate 2 random numbers from 3rd column [1 2 3].
The following code is what I've written to do this. It works but it seems not efficient especially when a is huge. Currently, I am using for-loop, may I know if anyone could have more efficient ways like the vectorized version to do this?
Thank you!
a=[0 1 0 0; 1 1 1 0; 1 0 0 1];
dind=1:3;
[a1,a2]=find(a==1);
e=[1 2 1 1];%define how many random numbers needed
d=cell(length(e),1);
for j=1:length(e)
c=a1(a2==j);%read the random number row index of j-th colomn
d{j}=dind(1,c(1:e(j)));%read the row index
a(c(1:e(j)),j)=0;%make the readed data into 0
end
  4 件のコメント
KSSV
KSSV 2018 年 5 月 3 日
Read about logical indexing......
Chaoyang Jiang
Chaoyang Jiang 2018 年 5 月 3 日
Thank you for your hint...

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

回答 (0 件)

カテゴリ

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