How to apply function on every pair of rows of a matrix?
4 次查看(过去 30 天)
显示 更早的评论
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:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/192785/image.jpeg)
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 个评论
回答(1 个)
Stephen23
2018-7-30
编辑:Stephen23
2018-7-30
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 个评论
Stephen23
2018-7-31
编辑:Stephen23
2018-8-1
@Soul Free: the screenshot in your question
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/193188/image.jpeg)
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!