### Translated by

このページのコンテンツは英語から自動翻訳されています。自動翻訳をオフにする場合は「<a class="turn_off_mt" href="#">ここ</a>」をクリックしてください。

## How to get the corresponding logic value based on the sum of vector elements

Zhou Liangyu

### Zhou Liangyu (view profile)

さんによって質問されました 2019 年 5 月 14 日

### Zhou Liangyu (view profile)

さんによって コメントされました 2019 年 5 月 16 日
Andrei Bobrov

### Andrei Bobrov (view profile)

さんの 回答が採用されました
I have a vector which is [1,1,2,3,5]; I want to loop through all the elements in the vector to check whether the sum of each elements is equal to my input. After that put the corresponfding index of the possible answer as a reference to a new vector which retrun the logic value. For example, if the inout is 6, the corresponding logic value suppose to be [1,0,0,0,1] or anyother combination. The problem is if the value is bigger than 8 it need the sum of 3 elements in vector. How I can get the same answer when the input need three elements add together?

#### 0 件のコメント

サインイン to comment.

## 1 件の回答

### Andrei Bobrov (view profile)

2019 年 5 月 14 日
採用された回答

A = [1,1,2,3,5];
my_input = 5;
out = [];
n = numel(A);
ii = 1:n;
for jj = 1:n
k = nchoosek(ii,jj);
r = sum(reshape(A(k),size(k)),2);
lo = r == my_input;
if any(lo)
p = k(lo,:);
m = size(p,1);
out = [out;accumarray([repmat(1:m,jj,1),p(:)],1,[m,n])];
end
end

Zhou Liangyu

### Zhou Liangyu (view profile)

2019 年 5 月 15 日
It return me the correct answer but I do not understand about the use of ' k = nchoosek(ii,jj);r = sum(reshape(A(k),size(k)),2);'those two steps. Could you please explain it a little bit?
Andrei Bobrov

### Andrei Bobrov (view profile)

2019 年 5 月 15 日
nchoosek(v,k) - returns a matrix containing all possible combinations of the elements of vector v taken k at a time.
reshape(A,sz) - reshapes A using the size vector, sz, to define size(B). For example, reshape(A,[2,3]) reshapes A into a 2-by-3 matrix. sz must contain at least 2 elements, and prod(sz) must be the same as numel(A).
Row
r = sum(reshape(A(k),size(k)),2);
we can change on block:
if jj == n
AA = Ak(k).';
else
AA = Ak(k);
end
r = sum(AA,2);
here
Ak = A(:);
Zhou Liangyu

### Zhou Liangyu (view profile)

2019 年 5 月 16 日
Thank you very much.

サインイン to comment.

Translated by