generate random numbers among each non zero column elements

1 次查看(过去 30 天)
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 个评论

请先登录,再进行评论。

回答(0 个)

类别

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