How to find the all the possible differneces between rows
1 次查看(过去 30 天)
显示 更早的评论
Hello For simplicity , if i have a table A=Randi(50,16) and i want to find the difference of each row with all the others, what is the fastest way to do this?For instance the difference A(1,:) with all the others( A(n,:),(n=2:50)), and after the A(2,:) with all the other rows including the first row (A(1,:),A(n,:),(n=3:50)) , and so on. Thank you
0 个评论
回答(1 个)
Star Strider
2016-3-13
I would use the Statistics Toolbox pdist function. If your data are actually in a table (table class variable), you might have to convert them to a matrix first because pdist may not work for table-class variables. (I cannot find any mention in the documentation that it supports tables.)
Since you want the difference, I chose to use the 'hamming' distance metric:
A = randi(50,16);
DistVct = pdist(A, 'hamming');
DistMtx = squareform(DistVct);
2 个评论
Star Strider
2016-3-13
The pdist function will so that. However it requires a scalar output from the distance function for each row-wise comparison, so it’s necessary to take the sum of the differences across each row of differences. (This is similar to the 'cityblock' distance function, without taking the absolute value.)
This works:
A = randi(50,16); % Create Data
dist = @(XI,XJ) sum(bsxfun(@minus,XI,XJ),2);
DistVct = pdist(A, dist);
DistMtx = squareform(DistVct);
The other option is the knnsearch (k-th nearest neighbour search). You would use the same ‘dist’ function I use here.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!