select few values from a vector randomly

조회 수: 3 (최근 30일)
Elysi Cochin
Elysi Cochin 2023년 2월 1일
편집: Tushar Behera 2023년 2월 1일
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

채택된 답변

Arif Hoq
Arif Hoq 2023년 2월 1일
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

추가 답변 (1개)

Tushar Behera
Tushar Behera 2023년 2월 1일
편집: Tushar Behera 2023년 2월 1일
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
Elysi Cochin
Elysi Cochin 2023년 2월 1일
편집: Elysi Cochin 2023년 2월 1일
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 2023년 2월 1일
take a look at the edited answer

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by