How can I create a loop that iterates thru +/- values of an array to find a solution?

1 回表示 (過去 30 日間)
Nick
Nick 2017 年 4 月 18 日
コメント済み: Nick 2017 年 4 月 21 日
Basically, the code I'm trying to write will take an array of data, sum it, and find the solution. The sum is known before hand, but whether the data values are positive or negative are not. I'm thinking I could do this using some sort of double for loop marking coefficients as either 1 or -1 but I'm stuck. Any advice? (I'll show an example)
clear,clc
summ = 2
data = [8, 12, 2]
%loops
%...
%SOLUTION
ans = [8 -12 6]
>>

採用された回答

Roger Stafford
Roger Stafford 2017 年 4 月 18 日
If ‘data’ is a row vector and ‘summ’ is the desired sum, do this:
n = length(data);
d = dec2bin(0:2^n-1,n)-0;
d = repmat(data,2^n,1).*(2*d-1);
f = find(sum(d,2)==summ);
s = d(f,:);
Each row of s should be a “solution” for you with appropriate sign changes, if any are found. It is assumed here that all elements of ‘data’ are integers - otherwise the exact equality requirement in the ‘find’ operation would be too demanding.
Warning: Beware of data vectors that are too long - they can result in an enormous ‘d’ array.
  1 件のコメント
Nick
Nick 2017 年 4 月 21 日
Thanks that works great! Much more efficient & effective than trying to use loops.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by