ismember(A,B,'rows') indexing
이전 댓글 표시
Hello everyone,
I would like to compare two cells, want to see if element of A is a member of B, If yes then it should return 1 otherwise 0.
Size of A is 189x1 and Size of B is 108x1.
I used:
C = ismember(A,B,'rows');
It returned logical o,1. With Size of 189x1, Perfect.
But now. I want Values of B (108x1) sorted same like C with Size 189x1.
Any help would be appreciated.
Thank you.
Regard,s
Waqar Ali
댓글 수: 4
Geoff Hayes
2019년 7월 11일
Waqar - please clarify what you mean by I want Values of B (108x1) sorted same like C with Size 189x1. Do you want B to be transformed from a 108x1 array into a 189x1 array?
Waqar Ali Memon
2019년 7월 11일
dpb
2019년 7월 11일
Well, that's easy enough -- add 81 elements on the end. The question is, what are the new elements to contain? I don't see there's any correlation between the two requests.
Waqar Ali Memon
2019년 7월 11일
채택된 답변
추가 답변 (2개)
joe
2019년 7월 11일
0 개 추천
function result = compareMatrices( A,B)
result = zeros(size(A,1),size(B,2)); % generate matrix with the same size as the A
for i=1:numel(A) % this loop checkes the existens of all elements of A in B
[~,index]=ismember(A{i,1},B);
if index~=0 % if any element of A exists in B
result{i,1} = 1; % set 1 in the same position where the existens detected
end
end
end
댓글 수: 5
Waqar Ali Memon
2019년 7월 11일
Guillaume
2019년 7월 11일
Functions need to go into their own files or at the end of a script file. You can't paste function definitions on the command line.
joe had the correct concept of using the 2nd return value of ismember. However, a loop is certainly not needed and just unnecessary complexity.
Waqar Ali Memon
2019년 7월 11일
joe
2019년 7월 11일
if you have matrices with elements of deferent types
try to call the function like this: compareMatrices(string(A), string(B))
Waqar Ali Memon
2019년 7월 14일
Guillaume
2019년 7월 11일
If the two cell arrays don't have the same number of columns, you're obviously not using ismember(A, B, 'rows') but something slightly more complex. I'm taking a guess here.
You also haven't said what needs to go in the result, when the row of A is not found in B.
In any case, you just have to use the 2nd output of ismember
[isfound, where] = ismember(A(:, 1), B(:, 1)); %compare column 1 of A and column 1 of B
C = [A(isfound), B(where(isfound), 3)]; %get rows of A found in B together with the matching value of column 3 of B
Adapt as necessary.
카테고리
도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!