Clear Filters
Clear Filters

How to find the all the possible differneces between rows

2 views (last 30 days)
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

Answers (1)

Star Strider
Star Strider on 13 Mar 2016
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 Comments
Alexandros Samp
Alexandros Samp on 13 Mar 2016
Hi
I want each number that is in the first row minus each number in every other row. But i want to know the first with the first the second with the second . if A=[3,4,5;5,7,8;1,2,3] then the first row of A(1,:)=3 4 5 minus 5 7 8 (3-5,4-7,5-8) and then 1 2 3 (3-1,4-2,5-3). After this i want to do the same with the second row ans so on .
Star Strider
Star Strider on 13 Mar 2016
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.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!