Power Set
조회 수: 24 (최근 30일)
이전 댓글 표시
I just got MatLab and I have to preform some simulations. To do them correctly I need to have the program run over all subsets of a given set of options. What is the easiest way to do this? Is there a package that already exists to do this in Matlab?
Thanks for any help!
댓글 수: 1
Paulo Abelha
2017년 5월 1일
You might want to use my funciton: https://uk.mathworks.com/matlabcentral/fileexchange/62752-powerset--s--
답변 (4개)
Joseph
2013년 10월 18일
편집: Joseph
2013년 10월 18일
function logical_indices = logical_indices_for_power_set(set_size)
%LOGICAL_INDICES_FOR_POWER_SET creates a cell array containing all possible
%combinations of logical indices to extract the members of a power set
%by indexing into the original set. This saves the memory overhead of
%storage of the set elements themselves, and instead only needs storage for
%the indices of the original set.
%2^N cells of logical indices each of [1 x set_size].
%Converts the sequence of numbers from 0 to 2^set_size-1 to binary string
%representation. The characters of the string are turned into ascii
%characters. 48 is the ascii code for zero, so testing for equality will a
%a matrix of logical indices, where the first row identifies all elements
%of the set.
logical_indices = mat2cell(double(dec2bin(0:2^set_size-1,set_size))==48,ones(2^set_size,1));
댓글 수: 0
Wayne King
2011년 10월 13일
How many items are you trying to do this for? This can get computationally expensive very fast. But combnk might help you.
% the set
x = 1:4;
for nn = 1:4
% all the combinations taken nn items at a time
combnz{nn} = combnk(x,nn);
end
댓글 수: 2
Wayne King
2011년 10월 13일
Yes each cell array will contain the elements of your set taken k at a time with each row of the cell array corresponding to one of the elements of the power set. Check the reference page for combnk() about trying this if the set has more than 15 elements.
holly chen
2016년 3월 26일
function PSet = PowerSet(SetA)
% Generate Power Set
% take input like {1,3,'B'}
% convert to {'1','3','B'}
SetB={};
for i=1:length(SetA)
if isnumeric(SetA{i})
SetB= union(SetB,[num2str(SetA{i}),' ']);
elseif ischar(SetA{i})
SetB= union(SetB,[SetA{i},' ']);
else
error('Error input');
end;
end;
Set= unique(SetB); % It is a set, no repeat elements
PSet = fPowerSet(Set);
for i=1:length(PSet)
PSet(i)=deblank(PSet(i)); %trimming
end;
end
function PSet = fPowerSet(Set)
if isempty(Set)
PSet={''};
return;
else
A = Set{1};
P = fPowerSet(setdiff(Set, A));
AP = {};
for i =1: length(P)
AP = union(AP, [A, P{i}]);
end
PSet = union(P, AP);
return;
end ;
end
testing case:
PowerSet({1,12,'A'})
ans: '' '1' '1 12' '1 12 A' '1 A' '12' '12 A' 'A'
댓글 수: 0
Paulo Abelha
2017년 5월 1일
You might want to use my funciton: https://uk.mathworks.com/matlabcentral/fileexchange/62752-powerset--s--
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!