Power Set
23 次查看(过去 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 中查找有关 .NET Methods in MATLAB 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!