Power set: Difference between revisions

Content added Content deleted
m (→‎{{header|MATLAB}}: Fixed a typo)
m (→‎{{header|MATLAB}}: Fixed a typo and changed a variable name so it doesn't conflict with any MATLAB keywords)
Line 780: Line 780:


Sets are not an explicit data type in MATLAB, but cell arrays can be used for the same purpose. In fact, cell arrays have the benefit of containing any kind of data structure. So, this powerset function will work on a set of any type of data structure, without the need to overload any operators.
Sets are not an explicit data type in MATLAB, but cell arrays can be used for the same purpose. In fact, cell arrays have the benefit of containing any kind of data structure. So, this powerset function will work on a set of any type of data structure, without the need to overload any operators.
<lang MATLAB>function pset = powerset(set)


Note: Although the keyword "set" is MATLAB function, MATLAB overrides any built-in keywords
pset = {zeros(size(set))}; %Preallocate memory

<lang MATLAB>function pset = powerset(theSet)

pset = {zeros(size(theSet))}; %Preallocate memory


%Generate all numbers from 0 to 2^(num elements of the set)-1
%Generate all numbers from 0 to 2^(num elements of the set)-1
for i = ( 0:(2^numel(set))-1 )
for i = ( 0:(2^numel(theSet))-1 )
%Convert i into binary, convert each digit in binary to a boolean
%Convert i into binary, convert each digit in binary to a boolean
%and store that array of booleans
%and store that array of booleans
indicies = logical(bitget(i,(1:numel(set))));
indicies = logical(bitget( i,(1:numel(theSet)) ));
%Use the array of booleans to extract the members of the original
%Use the array of booleans to extract the members of the original
%set, and store the set containing these members in the powerset
%set, and store the set containing these members in the powerset
pset(i+1) = {set(indicies)};
pset(i+1) = {theSet(indicies)};
end
end