i have a matrix like this:
A=[4,0,5,5;0,2,4,0;3,0,0,0;0,1,0,3;3,0,1,0;2,0,0,2;0,0,3,0;2,3,4,0]
And matrix B and C are row numbers derived from matrix A based on some condition.
B=[7;8]
C=[1;2;3;4;5;6]
I want to compare values of matrix B with each value of matrix C and find what nonzero indexes are common between both in matrix A.
for example: first value of B is 7 and it will be compared with all values of C. In first iteration, comparison will be 7 and 1 and result will be 3 because 3rd value is common nonzero value between both. Similarly:
result(7,2)=3
result(7,3)=0 (No nonzero index is common)
and similarly after 7, 8 will be compared with all values of C.
Please help on this.

댓글 수: 1

Tha saliem
Tha saliem 2017년 6월 10일
Also it is not necessary that values in B and C are sorted. It can be in any order

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

 채택된 답변

Andrei Bobrov
Andrei Bobrov 2017년 6월 10일
편집: Andrei Bobrov 2017년 6월 12일

0 개 추천

[EDIT 2]
A=[4,0,5,5;0,2,4,0;3,0,0,0;0,1,0,3;3,0,1,0;2,0,0,2;0,0,3,0;2,3,4,0];
B=[7;8];
[C,~] = find(bsxfun(@ne,(1:size(A,1))',B(:)'));
n = numel(B);
B1 = repelem(B,numel(C)/n);
k = squeeze(num2cell( bsxfun(@times,bsxfun(@and,A(C,:), A(B1,:)),1:size(A,2)),2 ));
result = cellfun(@nonzeros,k,'un',0);
result(cellfun(@isempty,result)) = {0}
result = reshape(result,[],n);

댓글 수: 6

hi thanks alot for your time. But it is showing correct result for row 7 but not for row 8.
result= {3;3;0;0;3;0} for 7
result= {[2;4];[3;4];2;3;[2;4];2} for 8
where it should be {[1;3];[2;3];1;2;[1;3];1}
Tha saliem
Tha saliem 2017년 6월 10일
one more thing is that what i have to do if i want to compare 7 with every other row in matrix like with 1 2 3 4 5 6 and also 8. and similarly 8 with rows from 1 to 7.
Tha saliem
Tha saliem 2017년 6월 10일
편집: Tha saliem 2017년 6월 10일
I tried it on a bigger matrix of 8 rows and 9 columns but results are different.
A=[4,0,0,5,0,0,4,5,0;0,2,4,0,0,3,0,0,5;3,0,0,0,4,0,3,0,0;0,1,0,3,0,2,0,0,4;3,0,1,0,4,0,3,5,0;2,0,0,2,0,0,4,0,0;0,0,3,0,0,0,0,0,2;2,3,4,0,4,1,3,0,5]
Andrei Bobrov
Andrei Bobrov 2017년 6월 10일
I'm corrected.
Tha saliem
Tha saliem 2017년 6월 10일
편집: Tha saliem 2017년 6월 11일
Thanks alot for helping. it gives following error:
Error using ~= Matrix dimensions must agree.
Error in test10 (line 31) [C,~] = find((1:size(A,1))' ~= B(:)');
Andrei Bobrov
Andrei Bobrov 2017년 6월 12일
Second correction

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

질문:

2017년 6월 10일

댓글:

2017년 6월 12일

Community Treasure Hunt

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

Start Hunting!

Translated by