MATLAB: Compute differences bewteen vectors in a matrix

matricesmatrixmatrix arraymatrix manipulation

Hi all, I have a question for you:
I have a matrix of the following type, where the i-th vector is a row vector:
A = [v1;v2;v3;v4;…;vN]
I want to compute all the possible differences between vectors, except the self-one. I mean: I need a first iteration that returns me [v1-v2;v1-v3;v1-v4;….;v1-vN] but I DON'T want to consider v1-v1; then at the next iteration I want [v2-v1; v2-v3; v2-v4;…;v2-vN] and i DON'T want v2-v2.
I need to do this for all the rows of my matrix A, I prefer to obtain only one difference-matrix at time because then I have to do some processing over it. So can you suggest me an algorithm that exactly does this?
Thanks

Best Answer

This is easy to achieve with basic indexing and an anonymous function:
>> A = randi(9,5,7)
A =
4 4 5 9 4 7 1
9 4 6 8 2 8 2
9 7 2 1 7 9 8
2 5 7 7 5 3 5
2 7 1 4 6 6 5
>> fun = @(k) A(k,:) - A([1:k-1,k+1:end],:);
>> fun(1)
ans =
-5 0 -1 1 2 -1 -1
-5 -3 3 8 -3 -2 -7
2 -1 -2 2 -1 4 -4
2 -3 4 5 -2 1 -4
>> fun(2)
ans =
5 0 1 -1 -2 1 1
0 -3 4 7 -5 -1 -6
7 -1 -1 1 -3 5 -3
7 -3 5 4 -4 2 -3
>> fun(3)
ans =
5 3 -3 -8 3 2 7
0 3 -4 -7 5 1 6
7 2 -5 -6 2 6 3
7 0 1 -3 1 3 3
>> fun(4)
ans =
-2 1 2 -2 1 -4 4
-7 1 1 -1 3 -5 3
-7 -2 5 6 -2 -6 -3
0 -2 6 3 -1 -3 0
>> fun(5)
ans =
-2 3 -4 -5 2 -1 4
-7 3 -5 -4 4 -2 3
-7 0 -1 3 -1 -3 -3
0 2 -6 -3 1 3 0