Calculating distance from a refence vector for a matrix

I have a matrix A and a reference vector ref I want to calculate the distance for each row of the matrix.
Example:
A = [1 2 3; 4 5 6; 7 8 9];
ref = [2 6 8];
distance = sqrt(sum((A(1,:) - ref) .^ 2));
How to do this for all the rows of A in a single line ?

 채택된 답변

Arpan Bhowmik
Arpan Bhowmik 2018년 4월 28일
You can use bsxfun to do the subtraction steps in one line as follows:
A = [1 2 3; 4 5 6; 7 8 9];
ref = [2 6 8];
distance = sqrt(sum(bsxfun(@minus,A,ref).^2,2));% Sum has to be given dimension
% to work on since input is matrix

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Sparse Matrices에 대해 자세히 알아보기

질문:

2018년 4월 28일

답변:

2018년 4월 28일

Community Treasure Hunt

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

Start Hunting!

Translated by