Combine different matrices to create a new one

I want to create matrix C, from matrix A and B.
A = (r1 r2 r3)
B=
[r1 r2
r3 r4
r2 r1
r5 r6
r2 r3
r3 r2
r3 r1
r1 r3]
C=(s1 s2 s3)
Matrix A and matrix C have the same size.
s1, s2, s3 are row’s number in matrix B. The row’s number in matrix B start from 0.
s1= bigger row’s number between r1 r2 and r2 r1
s2= bigger row’s number between r2 r3 and r3 r2
s3= bigger row’s number between r3 r1 and r1 r3
this is an example:
A= [4 1 6]
B= [4 1
6 8
1 6
1 4
6 1
6 4
4 6]
C= [3 4 6]
Any help would be appreciated.
Thank you very

 Accepted Answer

A= [4 1 6]
B= [4 1
6 8
1 6
1 4
6 1
6 4
4 6]
K = permute(hankel(A(1:2),[A(2:end),A(1)]),[3,1,2]);
P = repmat(B,1,1,numel(A));
[L1,~] = find(all(bsxfun(@eq,K,P),2));
[L2,~] = find(all(bsxfun(@eq,K(:,end:-1:1,:),P),2));
C = max([L1,L2].') - 1

12 Comments

Ali
Ali on 1 Jun 2016
Edited: Ali on 1 Jun 2016
Many thanks for the answer.
With your code, I got the following result:
C= [6 5 6]
But I need this one:
C= [3 4 6]
look at the following: for instance: s1 would be 0 and 3.
The bigger number between them is 3. So, s1 is 3.
Corrected, in result: C = [3 4 6]
Thanks a lot for the help.
But I need this:
C= [3 4 6]
I am really grateful.
You solved this problem and I thank you very much.
when I used the code for the real data, I got the following answer.
C =
Empty matrix: 0-by-1
Actually A contains 260 rows, but this code just works when A has only one row.
Could you please help me with this?
I still get this error:
C =
Empty matrix: 1-by-0
Ali
Ali on 1 Jun 2016
Edited: Ali on 1 Jun 2016
For instance the code does not work for the following:
A= [4 1 6;12 15 17]
B= [4 1
6 8
1 6
12 15
15 12
17 12
12 17
15 17
17 15
1 4
6 1
6 4
4 6]
C=[9 10 12
4 8 6]
What will be in C?
Many thanks for the answer.
C=[9 10 12
4 8 6]
I was wondering if you could help me here.
If you need A matrix with more rows, please tell me.
Thanks a lot.
m = size(A,2);
Y1 = reshape(permute(cat(3,A,circshift(A,[0 -1])),[3,2,1]),size(A,1),[]); %
Y2 = flip(Y1,1);
Bp = permute(B,[2,3,1]);
X = reshape(any([all(bsxfun(@eq,Y1,Bp));all(bsxfun(@eq,Y2,Bp))]),m*2,[])';
Z = reshape(max(bsxfun(@times,X,(1:size(B,1))')),m,[])'-1;
Thank you very much Andrei Bobrov. I am new in Matlab and you helped me a lot.
Thank you for your time and effort for solving this issue.

Sign in to comment.

More Answers (0)

Asked:

Ali
on 1 Jun 2016

Commented:

Ali
on 2 Jun 2016

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!