问题
I'm new to matlab and working with matrix and I'm kinda confused.
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 which calculates the sum of d(m(i,j),m(k,j)) in every column:
Please read the comment for an example.
How to find the sum?
I know basic programming but I don't know how to do this.
回答1:
You can use nchoosek for selction:
comb = nchoosek(1:size(m,1), 2);
result = zeros(1, length(comb)); % allocate the memory
% you can run some techniques to run a function on each row of comb
% which is mentinoned in other posts instead of the following code
for i = 1:length(comb)
result(i) = sum(abs(m(comb(i,1), :) - m(comb(i,2), :)) == 2);
end
来源:https://stackoverflow.com/questions/51579179/how-to-apply-a-function-on-every-pair-of-rows-of-a-matrix-in-matlab