1

I have two matrices in this form:

ind=
1
1
1
1
2
2
2
2
2
3
3

type = 
A
A
B
A
A
B
A
B
A
B
A

I want to be able to identify pairs of a specific kind i.e. A-B and B-A but not A-A. I have been able to do this using IF statements in this form:

if strcmp(type(m),'A') == 1 && strcmp(type(m+1),'B') == 1 && ind(m) == ind(m+1)

And so forth.

As hinted to within this IF statement, I need to be able to calculate how many valid pairs there are per index.

For example, the first four types AABA belong to index '1' because index '1' has a length of 4 as specified in ind. Here there are two valid pairs A-B and B-A. A-A is not a valid pair.

The desired output for the full above example would be:

2
4
1

Is there a quick and easy way to accomplish this?

EDIT:

If the types were expanded to include 'C' - and the system needs to detect non-unique pairs i.e. A-B, B-A but also B-B (but nothing containing C) - could this be done? Is there a way to specify which pairs are being counted each time?

AnnaSchumann
  • 1,261
  • 10
  • 22

2 Answers2

1

Try this:

>> arrayfun(@(x) sum(diff(type(ind == x)) ~= 0), unique(ind))

ans =

     2
     4
     1
Rafael Monteiro
  • 4,509
  • 1
  • 16
  • 28
  • +1 Very concise. Out of interest, could this be adapted to look for specific pairs? For example if my types were expanded to A/B/C and I wanted to find A-B, B-A and B-B (thus a non-unique pair) but nothing containing C, could this be done? – AnnaSchumann Jul 16 '15 at 17:20
1

You can try:

ind = [1 1 1 1 2 2 2 2 2 3 3]';  
type = 'AABAABABABA';
accumarray(ind(intersect([strfind(type,'AB'),strfind(type,'BA')],find(~diff(ind)))),1)

output:

ans =

     2
     4
     1

If I recall correctly, arrayfun is actually kind of slow. I don't think it actually vectorizes the code. Anyway, the idea is to find 'AB' and 'BA' with strfind and then merge the indices together. However, you cannot count 'AB' and 'BA' across index boundaries, so intersect with find(~diff(ind)) will make sure only valid indices are kept. Then accumarray will accumulate all the indices together with ind for the answer you want.

Community
  • 1
  • 1
JustinBlaber
  • 4,629
  • 2
  • 36
  • 57