필터 지우기
필터 지우기

Generating an "all-combinations" matrix for a given vector

조회 수: 1 (최근 30일)
Burak
Burak 2016년 11월 7일
편집: Andrei Bobrov 2016년 11월 8일
Hi,
Given a column vector with integer values, say x = [2;3;4], I would like to create a 3*24 matrix of the following form
Each column in A is created by selecting 1st, 2nd and 3rd elements of the corresponding column from sets {1,2}, {1,2,3} and {1,2,3,4}, respectively. Thus, 2*3*4=24 different columns can be generated using this approach to form matrix A.
I am aware that the number of columns in matrix A grows very fast with the size of vector x and numeric values of its elements. But I won't be working with examples of matrix A larger than 500 cloumns.
Thanks for your help,
-burak

채택된 답변

Thorsten
Thorsten 2016년 11월 7일
x = [2 3 4];
n = prod(x);
for i = 1:numel(x)
li = []; for ii = 1:x(i), li = [li repmat(ii, [1 n/prod(x(1:i))])]; end,
A(i,:) = repmat(li, [1 n/numel(li)]);
end
  댓글 수: 1
Burak
Burak 2016년 11월 7일
편집: Burak 2016년 11월 7일
This one works fine for my purpose. Thank you so much.

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Andrei Bobrov
Andrei Bobrov 2016년 11월 7일
편집: Andrei Bobrov 2016년 11월 8일
A = fullfact(x(end:-1:1));
A = flip(A,2)';
other way :)
x = [2 3 4]';
k = arrayfun(@(ii)1:ii,x(end:-1:1),'un',0);
[a,b,c] = ndgrid(k{:});
A = [c(:),b(:),a(:)]';
  댓글 수: 1
Burak
Burak 2016년 11월 8일
I knew there was a built-in function for it. Thanks.

댓글을 달려면 로그인하십시오.


KSSV
KSSV 2016년 11월 7일
clc; clear all ;
v1 = [1 2] ;
v2 = [1 2 3] ;
v3 = [1 2 3 4] ;
%
dimensions = cellfun(@numel, {v1,v2,v3});
[i1,i2,i3] = ind2sub(dimensions, 1:prod(dimensions));
combinations = [v1(i1); v2(i2); v3(i3)]
  댓글 수: 1
Burak
Burak 2016년 11월 7일
Thanks for the help. Though it works fine for the given instance,it requires to add a new i variable for each additional element in vector x.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Numeric Types에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by