Create a vector by selection randomly vectors
이전 댓글 표시
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.
채택된 답변
추가 답변 (2개)
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
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
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.
카테고리
도움말 센터 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!