Generation of a matrix based on a defined order of numbers
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Fayyaz
am 18 Okt. 2018
Kommentiert: Fayyaz
am 22 Okt. 2018
Hi all,
I need your help regarding the generation of a set of numbers.
Suppose, I have two vectors:
v1 = [2 3 4 5 6 7 8 9]
v2 = [3 4 5 6 7]
From v1, I would like to draw five numbers such that these five numbers include only (and any) two values of v1 (always only two numbers in the sequence), i.e.,
2 2 9 9 9
3 3 7 7 7
2 9 9 9 9
.........etc
Then I would like to draw five number from v2, however, the five numbers drawn from v1 are based on only one number that is (always one number in the sequence),
3 3 3 3 3
4 4 4 4 4
........
In the end, the sequences would include 10 numbers where every sequence of the five numbers drawn from v1 are combined with every other sequence of numbers drawn from v2. That is,
2 2 9 9 9 3 3 3 3 3
2 2 9 9 9 4 4 4 4 4
2 2 9 9 9 5 5 5 5 5
. ............
I would like to find out all the combinations that are possible, i.e., starting from
2 2 2 2 3 3 3 3 3 3
2 2 2 2 3 4 4 4 4 4
2 2 2 2 3 5 5 5 5 5
2 2 2 2 3 6 6 6 6 6
2 2 2 2 3 7 7 7 7 7
.........
.......
8 9 9 9 9 7 7 7 7 7
Many thanks.
0 Kommentare
Akzeptierte Antwort
Guillaume
am 19 Okt. 2018
One way to do it:
v1 = [2 3 4 5 6 7 8 9];
v2 = [3 4 5 6 7];
pick1 = nchoosek(v1, 2)';
idx1 = hankel([1 1 1 1 2], [2 2 2 2]) + permute(2*(0:size(pick1, 2)-1), [1 3 2]);
pick1 = reshape(pick1(idx1), 5, [])
pick2 = repmat(v2', 1, 5);
[pick2, pick1] = ndgrid(num2cell(pick2, 2), num2cell(pick1', 2));
result = cell2mat([pick1(:), pick2(:)])
Weitere Antworten (2)
Image Analyst
am 18 Okt. 2018
I believe this works:
v1 = [2 3 4 5 6 7 8 9]
v2 = [3 4 5 6 7]
% Get first vector of 5 numbers from v1.
twoIndexes = randperm(numel(v1), 2)
twoNumbers = sort(v1(twoIndexes))
index = randi(4)
firstVec = [twoNumbers(1) * ones(1, index), twoNumbers(2) * ones(1, 5 - index)]
% Get second vector of 5 numbers from v2.
secondIndex = randperm(numel(v2), 1)
secondVec = v2(secondIndex) * ones(1, 5)
% Stitch together to get the final vector.
finalVec = [firstVec, secondVec]
3 Kommentare
Image Analyst
am 19 Okt. 2018
A set of for loops can do it. Can't you figure it out?
What's the use case for this? Why do you want/need to do this unusual thing?
Andrei Bobrov
am 19 Okt. 2018
Bearbeitet: Andrei Bobrov
am 19 Okt. 2018
v1 = [2 3 4 5 6 7 8 9];
v2 = [3 4 5 6 7];
n = numel(v2);
q = nchoosek(v1,2)';
m = reshape(permute(...
q(2 - tril(ones(n-1,n)) + reshape(0:size(q,2)-1,1,1,[])),[2,1,3]),n,[])';
v = v2(:)*ones(1,5);
n2 = size(m,1);
out = [m(kron((1:n2)',ones(n,1)),:), repmat(v,n2,1)];
Added
m = reshape(permute(q( bsxfun(@plus,2 - tril(ones(n-1,n)),...
reshape(0:size(q,2)-1,1,1,[])) ),[2,1,3]),n,[])'; % for MATLAB <= R2016a
Siehe auch
Kategorien
Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!