-2

I am looking for a Matlab function, that help me to set a vector of integers, that multiplied by other known vector will be a sum of the other known integer.

For example:

V = [1, 2, 3, 4]
X = 10
results =
[10, 0, 0, 0] 
[8, 1, 0, 0]
.....
[0, 2, 0, 2]
etc.

I am trying to solve a problem similar to discrete knapsack problem.

user3448282
  • 2,629
  • 3
  • 25
  • 47
  • 2
    The problem statement is not clear. Can you restate it using mathematical formulae? Also, name all input and output variables and state their dimensions. – nojka_kruva Apr 28 '14 at 13:57
  • A set and a vector are not the same mathematical concept. You can't use them interchangeably. See the following link for explanation on this: http://math.stackexchange.com/questions/201518/what-is-the-difference-between-an-array-and-a-vector – nojka_kruva Apr 28 '14 at 14:02

1 Answers1

1

You could always use brute force (there may be more efficient approaches, though):

%// Data
V = [1 2 3 4];
X = 10;

%// Generate all combinations of n integers from 0 to X
%// (same approach as in http://stackoverflow.com/q/21895335/2586922 )
n = numel(V);
c = cell(1,n);
[c{:}] = ndgrid(0:X);
c = cat(n+1,c{:});
c = reshape(c,[],n);

%// Test which combinations are valid, and keep only those
s = sum(bsxfun(@times, c, V),2);
result = c(s==X,:);

In your example, there are 23 valid combinations:

result = 
    10     0     0     0
     8     1     0     0
     6     2     0     0
     4     3     0     0
     2     4     0     0
     0     5     0     0
     7     0     1     0
     5     1     1     0
     3     2     1     0
     1     3     1     0
     4     0     2     0
     2     1     2     0
     0     2     2     0
     1     0     3     0
     6     0     0     1
     4     1     0     1
     2     2     0     1
     0     3     0     1
     3     0     1     1
     1     1     1     1
     0     0     2     1
     2     0     0     2
     0     1     0     2
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • Many thanks! So clever idea :) Could you only tell me how could I get each vector? I write something like this: **n = result (1:1:4)**, but it return me **n = 10 8 6 4**, not **n = 10 0 0 0** – user3448282 Apr 28 '14 at 15:18
  • @user3448282 Each vector is a row of `result`. So you could use `n = result(1,:)` to get the first vector; `n = result(2,;)` to get the second etc – Luis Mendo Apr 28 '14 at 15:20
  • @LuisMendo Talking about understand questions, this was pure genius stuff (+1 for that), though I must admit I still can't fathom it, oh well :) – Divakar Apr 28 '14 at 21:26
  • @Divakar Thanks :-) But it's just a brute-froce approach; surely there are better ways... – Luis Mendo Apr 28 '14 at 21:28