Create a vector by selection randomly vectors

2 次查看(过去 30 天)
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 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by