generate random numbers among each non zero column elements

5 visualizaciones (últimos 30 días)
Chaoyang Jiang
Chaoyang Jiang el 18 de Abr. de 2018
Comentada: Chaoyang Jiang el 3 de Mayo de 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 comentarios
KSSV
KSSV el 3 de Mayo de 2018
Read about logical indexing......
Chaoyang Jiang
Chaoyang Jiang el 3 de Mayo de 2018
Thank you for your hint...

Iniciar sesión para comentar.

Respuestas (0)

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by