How to apply function on every pair of rows of a matrix?
7 views (last 30 days)
Show older comments
Hi, I'm new to matlab and I need help. I'm supposed to make a m x n matrix called M and it's elements are -1, 1 and 0.
I need to write a function called d(x,y) which returns 1 if (x = -1) and (y = 1). And returns 0 otherwise.
and another function called h(m(i),m(k)) which calculates the sum of d(m(i,j),m(k,j)) in every column and it is defined to find the distance between row i and row k:
For example Suppose M = [-1 0 -1; 1 -1 -1; 0 1 1].
If I calculate h for the 1st row and 2nd row(i = 1 and k = 2) it's Sum of d(m(1,j),m(2,j) for j from 1 to 3 which is d(m11,m21) + d(m12,m22) + d(m13,m23) = d(-1,1) + d(0,-1) + d(-1,-1) = 0+ 0 + 0 =0 .
Then I need h for every pair of rows. I'm confused. I tried writing d function as follows:
function d = d( x, y )
if (x==1) & (y==-1)
d = 1;
else
d = 0;
end
end
Then I tried to find h for row 1 and row 2 of the example matrix:
M = [-1 0 -1; 1 -1 -1; 0 1 1];
m=size(M,1);
n=size(M,2);
for i=1:2
h = sum(d(M(i,1:n)));
end
h returns 0 and works fine. I need to repeat this for every pair of matrix rows. For example for M which has 3 rows there will be 3 pairs of rows (3 choose 2) and h must be 1 x 3 (one sum for every pair).
0 Comments
Answers (1)
Stephen23
on 30 Jul 2018
Edited: Stephen23
on 30 Jul 2018
Perhaps something like this:
d = @(x,y)+(x==1&y==-1);
sum(bsxfun(d,permute(M,[1,3,2]),permute(M,[3,2,1])),3)
And tested:
>> M = [-1 0 -1; 1 -1 -1; 0 1 1]
M =
-1 0 -1
1 -1 -1
0 1 1
>> d = @(x,y)+(x==1&y==-1);
>> sum(bsxfun(d,permute(M,[1,3,2]),permute(M,[3,2,1])),3)
ans =
0 0 0
1 0 1
0 1 1
5 Comments
Stephen23
on 31 Jul 2018
Edited: Stephen23
on 1 Aug 2018
@Soul Free: the screenshot in your question
shows that the row indices i and k are not specified or summed over. As far as I can tell, this means you will have all combinations of rows i=1:m and k=1:m, thus giving an mxm matrix. If this is not the correct interpretation, please explain in more detail. It would also help if you provided the expected output for your example matrix M.
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!