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

1 view (last 30 days)
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?
  2 Comments
Stephen23
Stephen23 on 24 Feb 2020
Edited: Stephen23 on 24 Feb 2020
"What is the best way to create V?"
The Best Way: Simply by store your data in one matrix, then your task requires some basic array manipulation.
The Worst Way: Using numbered variables is a sign that you are doing something wrong. Accessing variable names is one way that beginners force themselves into writing slow, complex, buggy code that is hard to debug:

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 24 Feb 2020
Edited: Stephen23 on 24 Feb 2020
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

More Answers (0)

Products


Release

R2017a

Community Treasure Hunt

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

Start Hunting!