Computing the difference vector for all possible pairs of columns in a matrix?
조회 수: 2 (최근 30일)
이전 댓글 표시
I am trying to take a matrix like
A=[1 2 3 4; 5 6 7 8; 9 10 11 12]
and find a new matrix B such that
B = [A(:,1)-A(:,2), A(:,1)-A(:,3), A(:,1)-A(:,4), A(:,2)-A(:,3), A(:,2)-A(:,4), A(:,3)-A(:,4)]
(note that I'm ignoring the symmetric terms like A(:,2)-A(:,1) since that is just -(A(:,1)-A(:,2)) )
Is there any way to efficiently vectorize this process? My current method of doing a loop as below is slow
M=length(A(:,1))
N=length(A(1,:))
cnt=1;
for i=1:N-1
for j=i+1:N
B(:,cnt) = A(:,i)-A(:,j);
cnt=cnt+1;
end
end
댓글 수: 0
채택된 답변
Jos (10584)
2016년 4월 26일
Take a look at NCHOOSEK
A = [1 2 3 4 ; 10 8 6 4 ; 11 23 35 47]
ColIdx = nchoosek(1:size(A,2),2)
B = A(:,ColIdx(:,1)) - A(:,ColIdx(:,2))
An optimisation for nchoosek(V,2) can be found in NCHOOSE2, which you can download here: http://www.mathworks.com/matlabcentral/fileexchange/20144
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!