Effacer les filtres
Effacer les filtres

generate random numbers among each non zero column elements

1 vue (au cours des 30 derniers jours)
Chaoyang Jiang
Chaoyang Jiang le 18 Avr 2018
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 commentaires
KSSV
KSSV le 3 Mai 2018
Read about logical indexing......
Chaoyang Jiang
Chaoyang Jiang le 3 Mai 2018
Thank you for your hint...

Connectez-vous pour commenter.

Réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by