Azzera filtri
Azzera filtri

select few values from a vector randomly

2 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

Arif Hoq
Arif Hoq il 1 Feb 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')
v = 1×25
3 4 6 7 8 14 15 18 19 23 25 28 29 30 31 34 35 36 37 38 39 40 42 44 46

Più risposte (1)

Tushar Behera
Tushar Behera il 1 Feb 2023
Modificato: Tushar Behera il 1 Feb 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 Commenti
Elysi Cochin
Elysi Cochin il 1 Feb 2023
Modificato: Elysi Cochin il 1 Feb 2023
Sir, the values in output v repeats
v =
Columns 1 through 19
1 3 4 5 5 6 7 10 11 13 14 15 16 16 16 20 20 24 27
Columns 20 through 25
33 35 35 41 41 45
There should be no repetition in vector v.
All elements should be unique and values should be from v1 and v2 only
Tushar Behera
Tushar Behera il 1 Feb 2023
take a look at the edited answer

Accedi per commentare.

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by