Compute differences bewteen vectors in a matrix
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Gianluca Ligresti
am 13 Dez. 2018
Bearbeitet: Stephen23
am 13 Dez. 2018
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
0 Kommentare
Akzeptierte Antwort
Stephen23
am 13 Dez. 2018
Bearbeitet: Stephen23
am 13 Dez. 2018
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
0 Kommentare
Weitere Antworten (1)
KSSV
am 13 Dez. 2018
N = 10 ;
v = rand(N,1) ;
iwant = zeros(N-1,N) ;
for i = 1:N
idx = setdiff(1:N,i) ;
iwant(:,i) = v(i)-v(idx) ;
end
Siehe auch
Kategorien
Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!