Generation of a matrix based on a defined order of numbers
3 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
採用された回答
Guillaume
2018 年 10 月 19 日
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(:)])
その他の回答 (2 件)
Image Analyst
2018 年 10 月 18 日
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 件のコメント
Image Analyst
2018 年 10 月 19 日
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
2018 年 10 月 19 日
編集済み: Andrei Bobrov
2018 年 10 月 19 日
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
参考
カテゴリ
Help Center および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!