Reputation: 4373
Lets say I have the following vector in Matlab:
V = [4, 5, 5, 7];
How can I list (in a n-by-2 matrix for example) all the index pairs corresponding to unequal elements in the vector. For example for this particular vector the index pairs would be:
index pairs (1, 2) and (1, 3) corresponding to element pair (4,5)
index pair (1, 4) corresponding to element pair (4,7)
index pairs (2, 4) and (3, 4) corresponding to element pair (5,7)
The reason I need this is because I have a cost-function which takes a vector such as V
as input and produces a cost-value.
I want to see how does the random swapping of two differing elements in the vector affect the cost value (using this for steepest descent hill climbing).
The order of the index pairs doesn't also matter. For my purposes (1,2)
is the same as (2,1)
.
For example if my cost-function was evalCost()
, then I could have V = [4, 5, 5, 7]
and
evalCost(V) = 14
whereas for W = [4, 7, 5, 5]
the cost could be:
evalCost(W) = 10
How to get the list of "swapping" pair indexes in Matlab. Hope my question is clear =)
Upvotes: 2
Views: 855
Reputation: 112689
Use bsxfun
and then the two-ouput version of find
to get the pairs. triu
is applied to the output of bsxfun
to consider only one of the two possible orders.
[ii jj] = find(triu(bsxfun(@ne, V, V.')));
pairs = [ii jj];
Upvotes: 1
Reputation: 36710
I don't understand the cost function part, but the first part is simple:
[a,b]=unique(V)
C = combnk(b,2)
C
contains the indices, and V(C)
the values:
C = combnk(b,2)
C =
1 2
1 4
2 4
V(C)
ans =
4 5
4 7
5 7
Upvotes: 3