Create a vector with binary values {0,1} with certain percentage of 0's and 1's
    6 vues (au cours des 30 derniers jours)
  
       Afficher commentaires plus anciens
    
Hi all,
It may be a pretty simple question for many, but I cannot figure out the answer.
I am developing a simualtion in which 1 denotes device ON and 0 denotes OFF. My simulation has x% ON devices (and of course (1-x) %  OFF devices).
So, device 1 is denoted by element 1, dev. 2 by element 2 and so on...
In my simulation, I am working in vector mode (I avoid loops). 
How can I generate vector of Zeros and Ones (0,1) in which x% elements are 1, rest are 0.
I need something like this (randomly generated in each simulation run)
[1 1 1 0 1 1 0 0 1 0 1 1 0 0 1]
1 => Dev ON
0 => Dev OFF
0 commentaires
Réponse acceptée
  KSSV
      
      
 le 28 Mai 2020
        
      Modifié(e) : KSSV
      
      
 le 28 Mai 2020
  
      N = 10 ;   % total numner of elements 
O = 6 ;    % Number of 1 needed 
F = N-O ;  % Number of 0
O = ones(1,O) ; 
F = zeros(1,F) ;
T = [O F] ; 
idx = randperm(N) ;  % randomise the indices 
T = T(idx) 
1 commentaire
  KSSV
      
      
 le 28 Mai 2020
				Alternative a code with less steps: 
N = 10 ;   % total numner of elements 
O = 6 ;    % Number of 1 needed 
T = zeros(1,N) ; 
idx = randperm(N,O) ; 
T(idx) = 1 
Plus de réponses (0)
Voir également
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

