Create a vector by selection randomly vectors

조회 수: 1 (최근 30일)
Nikolas Spiliopoulos
Nikolas Spiliopoulos 2018년 11월 5일
댓글: Nikolas Spiliopoulos 2018년 11월 5일
Hi all,
I have 4 vectors
A=[1 2 3 4 5];
B=[0 2 5 6 19];
C=[0 0 1 3 0];
D=[1 0 1 15 0];
And I want to create vectors by randomly selecting from the list above, so that I take something like:
Vector1=[B;C;D;A]
Vector2=[C;D;A;B]
Vector3=[A;D;C;B]
.
.
.
etc.

채택된 답변

Stephan
Stephan 2018년 11월 5일
편집: Stephan 2018년 11월 5일
A=[1 2 3 4 5];
B=[0 2 5 6 19];
C=[0 0 1 3 0];
D=[1 0 1 15 0];
pool = [A; B; C; D];
n = 10 % Number of vectors to create
for k = 1:n
idx = randperm(4);
result(k,:) = [pool(idx(1),:), pool(idx(2),:), pool(idx(3),:), pool(idx(4),:)]
end
This code stores the created vectors in the lines of a Matrix. Access them with:
vector_1 = result(1,:)
vector_2 = result(2,:)
.
.
.
vector_n = result(n,:)
Best regards
Stephan

추가 답변 (2개)

Stephen23
Stephen23 2018년 11월 5일
편집: Stephen23 2018년 11월 5일
Having separate vectors is a pain to work with, so the first thing to do is to put them into one matrix M:
>> M = [1,2,3,4,5;0,2,5,6,19;0,0,1,3,0;1,0,1,15,0]
M =
1 2 3 4 5
0 2 5 6 19
0 0 1 3 0
1 0 1 15 0
>> N = 7; % how many output matrices
>> [~,R] = sort(rand(N,size(M,1)),2);
>> C = cellfun(@(r)M(r,:),num2cell(R,2),'uni',0);
>> C{:}
ans =
0 0 1 3 0
1 0 1 15 0
0 2 5 6 19
1 2 3 4 5
ans =
1 2 3 4 5
0 2 5 6 19
1 0 1 15 0
0 0 1 3 0
ans =
1 2 3 4 5
1 0 1 15 0
0 0 1 3 0
0 2 5 6 19
ans =
1 2 3 4 5
1 0 1 15 0
0 2 5 6 19
0 0 1 3 0
ans =
0 0 1 3 0
1 0 1 15 0
1 2 3 4 5
0 2 5 6 19
ans =
0 2 5 6 19
0 0 1 3 0
1 0 1 15 0
1 2 3 4 5
ans =
0 2 5 6 19
1 0 1 15 0
1 2 3 4 5
0 0 1 3 0

madhan ravi
madhan ravi 2018년 11월 5일
편집: madhan ravi 2018년 11월 5일
EDITED
A=[1 2 3 4 5]; B=[0 2 5 6 19]; C=[0 0 1 3 0]; D=[1 0 1 15 0];
vectors = [A;B;C;D];
n = 10 ; % specify n to create n number of vectors
VECTORS = cell(1,n); %PREALLOCATION
for i = 1:n
VECTORS{i}=[vectors(randsample((1:4),4) ,:)];
end
celldisp(VECTORS)
  댓글 수: 1
Stephen23
Stephen23 2018년 11월 5일
편집: Stephen23 2018년 11월 5일
Note that randi can repeat values in its output array, so this answer does not match the examples given (which do not repeat any rows and are all row permutations of the same matrix).
For example:
>> randi([1,4],2,2)
ans =
1 4
1 4
Would return A,A,D,D: where are B and C ?
One solution is to use randperm, as Stephan Jung's answer shows.

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

카테고리

Help CenterFile Exchange에서 Dates and Time에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by