# Extracting all possible vectors from a big vector

조회 수: 3(최근 30일)
Mehmet Fatih 2021년 6월 12일
편집: DGM 2021년 6월 12일
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표시숨기기 이전 댓글 수: 1
Mehmet Fatih 2021년 6월 12일
I am trying to make a code for this: Given a vector x, return the indices to elements that will sum to exactly half of the sum of all elements.
To use "sum" ı need them to be vector.
I will use it for vectors that are not long. At most 6 elements

댓글을 달려면 로그인하십시오.

### 채택된 답변

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)
C{1} = 1 C{2} = 2 C{3} = 3 C{4} = 4 C{5} = 1 2 C{6} = 1 3 C{7} = 1 4 C{8} = 2 3 C{9} = 2 4 C{10} = 3 4 C{11} = 1 2 3 C{12} = 1 2 4 C{13} = 1 3 4 C{14} = 2 3 4 C{15} = 1 2 3 4
(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표시숨기기 없음
Mehmet Fatih 2021년 6월 12일
Thank you for your answer. It really helped me. I will not use it for long vectors.

댓글을 달려면 로그인하십시오.

### 추가 답변(1개)

SALAH ALRABEEI 2021년 6월 12일
편집: SALAH ALRABEEI 2021년 6월 12일

댓글을 달려면 로그인하십시오.

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by