Create a vector by selection randomly vectors
1 回表示 (過去 30 日間)
古いコメントを表示
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.
0 件のコメント
採用された回答
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
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
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 件のコメント
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 Center および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!