MATLAB: What is the best way to create a vector with a special sequence of subvectors

loopMATLABmatrix manipulation

I have say 100 vectors of equal size (v1 to v100) and I want to create a vector V of the following structure: V=[v1-v2 ;…; v1-v100; v2-v3; … , v2-v100; …. …. …. ; v98-v99 ; v98-v100; v99-v100]. What is the best way to create V?

Best Answer

Store the vectors in one matrix, then you just need to use nchoosek to generate the required indices:
>> M = randi(9,5,3) % each row = one vector
M =
5 6 9
9 2 5
4 5 1
4 8 2
9 6 6
>> X = nchoosek(1:size(M,1),2);
>> Z = M(X(:,1),:) - M(X(:,2),:)
Z =
-4 4 4
1 1 8
1 -2 7
-4 0 3
5 -3 4
5 -6 3
0 -4 -1
0 -3 -1
-5 -1 -5
-5 2 -4