Making Pairs of Indices in Matrix- Pairwise Function

Hello,
I want to make a pairwise function in matlab simialar to how it is done in python. Or is there one already in matlab?
Overall, I am trying to return a list of pairs of indices in my matrix and then take the distance between each pair.
Any input would be greatly appreciated.
Thank you!

 Accepted Answer

Matt J
Matt J on 16 Jun 2020
Edited: Matt J on 16 Jun 2020
It depends what Matlab data-type you consider to be the equivalent of a Python tuple. I tend to think of cell arrays as the equivalent of a tuple because cells can store sequences of mixed types, but matrix form is generally the form in Matlab that will support most mathematical operations you might want to do. Below, I generate a set of pairs in both matrix and cell array form.
n=4;
pairMatrix=[0:n-1;1:n].';
pairCell=num2cell(pairMatrix,2)
Overall, I am trying to return a list of pairs of indices in my matrix and then take the distance between each pair.
You mean, the Euclidean distances when each pair is viewed as a 2D coordinate? If you have the Statistics Toolbox, then this can be done using pdist2,
>> pdist2(pairMatrix,pairMatrix)
ans =
0 1.4142 2.8284 4.2426
1.4142 0 1.4142 2.8284
2.8284 1.4142 0 1.4142
4.2426 2.8284 1.4142 0

4 Comments

What I am trying to get out is more like this:
If you had a list of numbers [1,2,3,4] , the pairwise function would return [(1,2),(2,3),(3,4)].
My matrix is very large and binary but I would put this parwise function to each individual row first.
For example,
row = [0,0,1,0,0,1,0,0,0,0,1] so the non zero values are at 3,6, and 11
i need something that would output: pairwise = [(3,6),(6,11)] so i could take the distance between each pair in a pairwise and then replace the zeros in between the nonzeros with their respective distance between them
To get something like this
row = [0,0,1,3,3,1,5,5,5,5,1]
Here's one way to do that:
row = double([0,0,1,0,0,1,0,0,0,0,1]);
loc=find(row); %locations of 1's
D=diff(loc); %differences
j=0;
for i=loc(1):loc(end)
if row(i)==1,
j=j+1;
else
row(i)=D(j);
end
end
row,
Here's another, without loops:
row = double([0,0,1,0,0,1,0,0,0,0,1]);
loc=find(row); %locations of 1's
D=diff(loc); %differences
c=cumsum(row); %cumulative sum along row
mask=c>=1 & c<=numel(D) & ~row; %binary mask of the 0's that are sandwiched by 1's
row(mask)=D(c(mask))
Thank you so much! This definitley helped!
You're quite welcome, but please Accept-click the answer to signify that you are satisfied with the solution.

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!