# Generate a random logical vector of a given size with a given number of true values?

20 visualizzazioni (ultimi 30 giorni)
Ela Markovic il 8 Dic 2022
Commentato: Jiri Hajek il 8 Dic 2022
How can I generate random logical vector with the set number of true values?
E.g. I want a vector with 10 elements that has 7 true values:
[1 1 1 0 0 1 1 0 0 0]
[1 1 0 1 0 1 1 0 0 0]
...
I tried something like:
random_num = zeros(1,10); % generates vector of 10 zero values
num_true_val = 7; % wanted number of true values
Sum = sum(random_num);
while Sum<num_true_val
position = randi([1 width(random_num)],1,1); % generate random position btw 1 and 10
random_num(1,position) = 1; % pin value of 1 to that position
Sum = sum(random_num); % calc sum again
random_num = logical(random_num)
end
disp(random_num)
1 0 0 1 1 1 0 1 1 1
This does the job but seems too long and I feel like there might be a better solution.
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Risposta accettata

Jiri Hajek il 8 Dic 2022
Hi, ince the number of true values is known beforehand, the problem may be translated as just picking random positions, where to place them. This may be easily done using randi function:
N = 10; % generates vector of 10 zero values
random_num = zeros(1,N); % initialize with zeros
num_true_val = 7; % wanted number of true values
random?num(randi(N,1,num_true_val)) = 1;
##### 2 CommentiMostra NessunoNascondi Nessuno
Ela Markovic il 8 Dic 2022
Your solution doesn't work because randi can select one value twice.
But if I switch randi for randperm then it works! Thank you, your solution is really simple.
So the final would be:
N = 10; % generates vector of 10 zero values
random_num = zeros(1,N); % initialize with zeros
num_true_val = 7; % wanted number of true values
random_num(randperm(N,num_true_val)) = 1;
Jiri Hajek il 8 Dic 2022
Sorry for that glitch. You deserve the credit.

Accedi per commentare.

### Categorie

Scopri di più su Logical in Help Center e File Exchange

R2022a

### Community Treasure Hunt

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

Start Hunting!

Translated by