problem with combvec, allcomb
14 次查看(过去 30 天)
显示 更早的评论
How to use combvec for a huge set (a1 to a100)?
Example a1=[1 3 4], a2=[5 7], a3=[7 9 1], .... a100=[8 9 6 2]
5 个评论
Walter Roberson
2012-11-9
The number of results you will get will be the product of the number of elements in the sets. That could be quite a lot!!
回答(2 个)
Andrei Bobrov
2012-11-10
编辑:Andrei Bobrov
2012-11-11
a = {1,3,[2 6 4],[8 9]};
c = cell(size(a));
[c{:}] = ndgrid(a{end:-1:1});
c2 = sortrows(cell2mat(cellfun(@(x)x(:),c,'un',0)),1);
out = fliplr(c2)';
ADD
n = cellfun(@numel,a);
t = max(n)./n;
while any(rem(t,1) ~= 0)
t = t*2;
end
c = cellfun(@(x,y)repmat(x,1,y),a,num2cell(t),'un',0);
out = cat(1,c{:});
Matt Fig
2012-11-9
This will solve your problem.
function M = expand_vects(A)
% A is a cell array of 1-by-n vectors where n need not
% be the same in every element.
L = cellfun('length',A);
B = lcms(L);
M = zeros(length(L),B);
for ii = 1:length(L)
M(ii,:) = reshape(A{ii}(ones(1,B/L(ii)),:).',1,B);
end
Once you have the files in place, call like this:
>> A = {1,3,[2,6,4],[8,9]}; % Use a cell array
>> M = expand_vects(A)
M =
1 1 1 1 1 1
3 3 3 3 3 3
2 6 4 2 6 4
8 9 8 9 8 9
2 个评论
Matt Fig
2012-11-9
You can forgo the FEX function and just use this. (I found that recursively calling LCM is just as fast or faster than the FEX function.)
function M = expand_vects(A)
% A is a cell array of 1-by-n vectors where n need not
% be the same in every element.
L = cellfun('length',A);
LC = length(L);
% B = lcms(L); % Available on the FEX. Or use below loop.
B = L(1);
for ii = 2:LC
B = lcm(B,L(ii));
end
M = zeros(LC,B);
L = B./L;
for ii = 1:LC
M(ii,:) = reshape(A{ii}(ones(1,L(ii)),:).',1,B);
end
Matt Fig
2012-11-10
Well.....
Simply make yourself a cell array and pass it in:
a1 = 1;
a2 = 3;
a3 = [3 4 5];
A = {a1,a2,a3};
Nasty problems like this are the reason we don't make variables a1,a2,a3,a4.....an in the first place.....
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!