Extracting all possible vectors from a big vector
2 次查看(过去 30 天)
显示 更早的评论
Hi guys,
İ want to expalin with an example. Let's say i have a vector [1 2 3 4] i want to extract these [1] [2] [3] [4] [1 2] [1 3] [1 4] [2 3] [2 4] [3 4] [1 2 3] [1 2 4] [1 3 4] [2 3 4] [1 2 3 4] i found a way to do that but the problem is that they are not vectors.
How can i do that?
I know that [2 3] and [3 2] are different vectors but order is not important.
v=[1 2 3 4];
b=length(v);
i=1;
while i<=b
a = uint16(v);
c = nchoosek(a,uint16(i));
disp(c)
i=i+1;
end
2 个评论
Image Analyst
2021-6-12
Why do you want to do this? What is the use case? The number of output vectors would blow up incredibly fast for more than a length of a few. Like if you had a vector that was hundreds long, it would be impractical.
采纳的回答
DGM
2021-6-12
编辑:DGM
2021-6-12
Sure they're vectors.
v=[1 2 3 4];
v = uint16(v); % there's no point doing this repeatedly in the loop
C = {};
for k = 1:numel(v)
c = nchoosek(v,k); % class is inherited from v
C = [C; num2cell(c,2)]; % one result per cell
end
format compact
celldisp(C)
(scroll to see the rest of the output)
Of course, IA is right. If v is very long at all, the problem becomes impractical. If the range of values in v allows, you might be able to save some weight by using uint8(). Still, even when using uint8(v), the result for a vector of length 25 occupies 4.2GB in RAM.
EDIT:
For what it's worth, we can save some time (might be valuable if n gets larger than about 20) by actually calculating how big C needs to be. I just let the array grow last time, but that was just me being lazy.
% calculate how large C needs to be
n = numel(v);
s = factorial(n)./(factorial((1:n)).*factorial(n-(1:n)));
sc = [0; cumsum(s)]; % this makes indexing easier
C = cell(sum(s),1); % allocate output
for k = 1:n
c = nchoosek(v,k);
C(sc(k)+(1:s(k))) = num2cell(c,2);
end
The time savings are maybe 10-20%, though that probably varies with version, hardware, and environment.
更多回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!