- Generate combinations with repetition by creating all possible combinations using ndgrid to cover repeated elements, such as [1, 1], [2, 2], etc.
- Flatten the grids into vectors to simplify manipulation.
- Filter the combinations to ensure that they are in non-decreasing order (e.g., keeping [1, 2] but discarding [2, 1]), so that the order of elements doesn't matter.
how to calculate perms for cell array vector
2 次查看(过去 30 天)
显示 更早的评论
hi
i wanted to add repeation to cell arrays e.g i have [1,2] but dont have [1,1] or [2,2] i wanted to add this for all cell arrays, thank you
vec = 1:10;
n=5;
fun = @(n)num2cell(combnk(vec,n),2);
out = arrayfun(fun,1:5,'uniformoutput',0);
out = vertcat(out{:});
for i=1:length(out)
a(i,1)=sum(cell2mat(out (i,:)))<=10;
end
ind = find (a(:,1)==0);
out(ind,:)=[];n;
0 个评论
回答(1 个)
Shlok
2024-9-6
Hi Mohamad,
I understand that you want to include repetition in the cell arrays, but you're unable to achieve this because you're using the “combnk” function, which only creates combinations without repetition. To address this, you'll need to modify your approach to generate combinations with repetitions. Here’s how you can do it:
Here’s how you can modify your code to include repetition:
% Our custom function to generate combinations with repetition
function combinations = generate_combinations_with_repetition(elements, n)
if n == 1
% For n=1, output each element in its own array
combinations = elements(:);
else
[idx{1:n}] = ndgrid(1:numel(elements)); % Creating all possible combinations
idx = cellfun(@(x) x(:), idx, 'UniformOutput', false); % Flattening the grids into vectors
% Filtering the combinations to ensure that they are in non-decreasing order
idx_matrix = [idx{:}];
valid_idx = all(diff(idx_matrix, 1, 2) >= 0, 2); % Keep only non-decreasing rows
combinations = elements(idx_matrix(valid_idx, :));
end
end
% Given code
vec = 1:10;
n = 5;
fun = @(n) num2cell(generate_combinations_with_repetition(vec, n), 2);
out = arrayfun(fun, 1:n, 'UniformOutput', false);
out = vertcat(out{:});
for i = 1:length(out)
a(i,1) = sum(cell2mat(out(i,:))) <= 10;
end
ind = find(a(:,1) == 0);
out(ind,:) = [];
disp(out);
In this modification, “generate_combinations_with_repetition” generates combinations with repetition and the rest of your code remains unchanged, ensuring combinations with sums greater than 10 are removed.
To know more about “ndgrid”, refer the following documentation link:
Hope it helps.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!