select few values from a vector randomly
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Elysi Cochin
le 1 Fév 2023
Modifié(e) : Tushar Behera
le 1 Fév 2023
v1 = [3 4 7 14 15 18 23 25 28 31 34 36 37 38 39 40 42 44 46];
v2 = [1 2 5 6 8 9 10 11 12 13 16 17 19 20 21 22 24 26 27 29 30 32 33 35 41 43 45 47];
I have 2 vectors v1 and v2
v1 has 19 columns and v2 has 28 columns
I wanted to create a new vector v of size 25 with all elements of v1 and if the size of v is not 25 I need to select few numbers from v2 randomly so as to make the size of v = 25 and write it in a sorted order
0 commentaires
Réponse acceptée
Arif Hoq
le 1 Fév 2023
try this:
v1 = [3 4 7 14 15 18 23 25 28 31 34 36 37 38 39 40 42 44 46];
v2 = [1 2 5 6 8 9 10 11 12 13 16 17 19 20 21 22 24 26 27 29 30 32 33 35 41 43 45 47];
target=25;
matsise=numel(v2);
a=v2(randperm(matsise,target -length(v1)));
v=sort([v1 a],'ascend')
0 commentaires
Plus de réponses (1)
Tushar Behera
le 1 Fév 2023
Modifié(e) : Tushar Behera
le 1 Fév 2023
Are you looking for something like this
v1 = [3 4 7 14 15 18 23 25 28 31 34 36 37 38 39 40 42 44 46];
v2 = [1 2 5 6 8 9 10 11 12 13 16 17 19 20 21 22 24 26 27 29 30 32 33 35 41 43 45 47];
v1=unique(v1);
v2=unique(v2);
num1=numel(v1);
num2=numel(v2);
v=zeros(1,25);
v=[v1]
if num1<25
for i=(num1+1):25
index = randi(numel(v2));
randomElement = v2(index);
if ismember(randomElement,v1)
%do nothing
else
v(i)=randomElement;
end
end
end
v=sort(v)
2 commentaires
Voir également
Catégories
En savoir plus sur Logical 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!