필터 지우기
필터 지우기

Compute differences bewteen vectors in a matrix

조회 수: 2 (최근 30일)
Gianluca Ligresti
Gianluca Ligresti 2018년 12월 13일
편집: Stephen23 2018년 12월 13일
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

채택된 답변

Stephen23
Stephen23 2018년 12월 13일
편집: Stephen23 2018년 12월 13일
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

추가 답변 (1개)

KSSV
KSSV 2018년 12월 13일
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
  댓글 수: 1
Gianluca Ligresti
Gianluca Ligresti 2018년 12월 13일
This code work over your v, that is a row vector. Instead I have a MATRIX A and I have to perform the differences between row vectors, so this solution doesn't work for my case

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by