Building matrix of differences
조회 수: 1 (최근 30일)
이전 댓글 표시
Say I have a vector v=[v1,...,vn].'. How can I generate the matrix D with components D(i,j) = vi - vj ? The dimension of the vector n is very large, so efficiency matters. Ideally I would like to generate the following matrix E(i,j) = 1/(vi-vj) for vi ~= vj (which we may assume corresponds to i~=j) and E(i,i) = 0.
Is there a fast way to do it? Doing it with loops is very slow.
Thanks a lot,
L
댓글 수: 0
답변 (1개)
Star Strider
2017년 5월 19일
See if this does what you want:
v = randi(9, 1, 5); % Create Data
D = bsxfun(@minus, v, v'); % Subtract To Create Matrix
Dnz = D~=0; % Logical Matrix (Becomes Numeric)
Dinv = Dnz./D; % Element-Wise ‘Inverse’
Note that ‘0/0’ become NaN values.
댓글 수: 2
Star Strider
2017년 5월 19일
My pleasure!
To convert the NaN values to 0, add this assignment to my previous code:
Dinv(~Dnz) = 0; % Convert ‘NaN’ To ‘0’
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!