Create a vector by selection randomly vectors
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Nikolas Spiliopoulos
el 5 de Nov. de 2018
Comentada: Nikolas Spiliopoulos
el 5 de Nov. de 2018
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 comentarios
Respuesta aceptada
Stephan
el 5 de Nov. de 2018
Editada: Stephan
el 5 de Nov. de 2018
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
Más respuestas (2)
Stephen23
el 5 de Nov. de 2018
Editada: Stephen23
el 5 de Nov. de 2018
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 comentarios
madhan ravi
el 5 de Nov. de 2018
Editada: madhan ravi
el 5 de Nov. de 2018
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 comentario
Stephen23
el 5 de Nov. de 2018
Editada: Stephen23
el 5 de Nov. de 2018
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.
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!