[R] euclidean dist. between matrices

David L Carlson dcarlson at tamu.edu
Sun Nov 18 04:19:53 CET 2012


I may not understand correctly, but you have a matrix A with 15 rows
and 365 columns and a second matrix B with 1 row and 365 columns.
You say you want to compute the Euclidean distance between the first
column of A (15 numbers) against B. That won't work since the first
column of B is a single number, so I assume you want to compare each
row of A with the single row of B computing a total of 15 Euclidean
distances. If that is correct, there are a couple of possibilities:

sapply(1:15, function(x) sqrt(sum((B-A[x,])^2)))

Another approach would be to use function dist() and throw away the
distances you don't need:

head(dist(rbind(B, A)), 15)

----------------------------------------------
David L Carlson
Associate Professor of Anthropology
Texas A&M University
College Station, TX 77843-4352


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of eliza botto
> Sent: Saturday, November 17, 2012 8:08 PM
> To: r-help at r-project.org
> Subject: [R] euclidean dist. between matrices
> 
> 
> Dear Users,I have two matrices A=15*365 and B=1*365. i want to
> calculate "Euclidean Distance" between these matrices in such a
way
> that i should have euclidean distance of matrix B against all the
> columns of matrix A. More precisely, first i want euclidean dist.
of
> column 1 of A against B, then column 2 against B, 3rd column of A
> against B and so on.is there a way in r to do it?your help is
deeply
> appreciated..
> eliza
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-
> guide.html
> and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list