How to find shared elements in a matrix

조회 수: 10 (최근 30일)
Saleh Almasabi
Saleh Almasabi 2017년 3월 12일
답변: Roger Stafford 2017년 3월 13일
Hi,
I have a zeros and ones vector called P. And a zeros and ones matrix called A, the matrix has a size nXn. The ones index in vector P, represents the raw in matrix A. For example if P=[0 1 0 1 0 0], then the corresponding rows in A are rows 2,4.
  1. (shared directly) I would like to find if A(2,4) or A(4,2) are both ones. The output is 4,2
  2. (shared indirectly) Now I want to find which elements i A(2,:) and A(4,:) are shared e.g have the same value. for example A(2,3) and A(4,3) both have ones, then I would get 3. The output is [2,3],[4,3]
I only care about the ones in both the vector P and matrix A. I have no interest in zero elements.
  댓글 수: 2
Geoff Hayes
Geoff Hayes 2017년 3월 12일
Saleh - will your P array only ever have two ones (so you will only be ever comparing two rows)? Or can P have more than two ones in which case you would be comparing every possible row pair?
Saleh Almasabi
Saleh Almasabi 2017년 3월 12일
Hi Geoff,
The P array might have two or more ones. I might need to compare two or more. I thought of adding the corresponding rows in A, two at a time. Then I would use the (find) command. (long but will work)
But the shared indirectly, especially if its (three layers) or more, is going to be tricky.

댓글을 달려면 로그인하십시오.

채택된 답변

Roger Stafford
Roger Stafford 2017년 3월 13일
D = nchoosek(find(P==1),2);
D = D(A(D(:,1)+n*(D(:,2)-1))==1 & A(D(:,2)+n*(D(:,1)-1))==1,:);
The two elements in each row of D are the possible indices such as 2,4 you mentioned in the “shared directly” part.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by