I want sum of two vectors at time from set of n vectors for eg;
A1=[1 2 3]
A2=[2 3 4]
A3=[3 4 5]
.
.
.
An=[6 6 9]
I want sum of (Ai + Aj) for all values of i and j. so if n=10 then I need all combinations i.e. 10*9/2
I want sum of two vectors at time from set of n vectors for eg;
A1=[1 2 3]
A2=[2 3 4]
A3=[3 4 5]
.
.
.
An=[6 6 9]
I want sum of (Ai + Aj) for all values of i and j. so if n=10 then I need all combinations i.e. 10*9/2
Here's a way to compute it manually, assuming the set of n vectors is stored in a matrix A
, row by row:
Obtain all possible pairs of indices (see this question for possible answers). For instance:
[idx2, idx1] = find(ones(N, N));
The corresponding pairs are given by:
pairs = [idx1(:), idx2(:)];
Alternatively, if you're not interested in repetitions (e.g. you don't want the sum A1+A1, etc.), you can use nchoosek
:
pairs = nchoosek(1:N, 2)
idx1 = pairs(:, 1);
idx2 = pairs(:, 2);
Use each pair of indices to sum the corresponding rows in A
:
sums = A(idx1(:), :) + A(idx2(:), :);
Alternatively, if you want the total sum of elements for each pair of Ai and Aj, you can do sum(A(idx1(:), :) + A(idx2(:), :), 2)
instead.
Here's an example for N = 3
:
A = [1 2 3; 2 3 4; 3 4 5];
N = size(A, 1);
[idx2, idx1] = find(ones(N, N));
pairs = [idx1(:), idx2(:)];
sums = A(idx1(:), :) + A(idx2(:), :);
The result is:
pairs =
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
sums =
2 4 6
3 5 7
4 6 8
3 5 7
4 6 8
5 7 9
4 6 8
5 7 9
6 8 10
Have a look at pdist
pdist(X) computes the Euclidean distance between pairs of objects in m-by-n data matrix X. Rows of X correspond to observations, and columns correspond to variables.
And define your own custom metric which will just be a function that sums two vectors (although I have a feeling that @plus
will work in your case i.e. pdist(X, @plus)
)
Lets have a try, as I am not sure whether you want a list of vectors as output or a list of sums I will give you both.
A1=[1 2 3]
A2=[2 3 4]
A3=[3 4 5]
An=[6 6 9]
First of all make sure everything is put together in a matrix (Can be automated if required, but I hope you can get this matrix as input)
A = [A1;A2;A3;An]
Now we can just use a small loop to simply work on the combinations:
n = size(A,1);
m = size(A,2);
nr_comb = (n*(n-1))/2;
pair = zeros(nr_comb,2);
result = zeros(nr_comb,m);
count = 0;
for i = 1:n-1;
for j = i+1:n
count = count +1;
pair(count,:) = [i j];
result(count,:) = A(i,:) + A(j,:);
end
end
Now assuming you actually want the sums of the combinations of vectors you can easily get them like so:
sumresult = sum(result')
It should not be too hard to add the symmetric variation, or the case where you combine a vector with itself, but given the number of combinations that you expect, this should be what you are looking for.