ismember has different length depending on argument order
조회 수: 4 (최근 30일)
이전 댓글 표시
I have 3 arrays with two columns each. Array 2 contains indices of matches between column1 of array 1 and 3.
Now I only want to keep rows in arrays 1 and 3, which are represented in array 2.
I'm using this code right now:
mask1 = ismember(array2(:,1), array1);
mask2 = ismember(array2(:,2), array3);
mask1 = logical(mask1.*mask2)
array2 = array2(mask1,:);
mask3 = ismember(array1, (array2(:,1)));
array1 = array1(mask3,:);
mask4 = ismember(array3, (array2(:,2)));
array3 = array3(mask4,:);
The problem is, that
ismember(array1, (array2(:,1)))
has a different length than
ismember((array2(:,1)), array1)
even I just switched the arguments position.
Is there anyone who can explain to me why this can happen and how to fix it?
댓글 수: 0
채택된 답변
Felix Bertoli
2021년 8월 1일
댓글 수: 1
Image Analyst
2021년 8월 1일
Again, you can simplify it and just use logical indexing rather than the confusing ismember(). It will be simpler and more intuitive.
추가 답변 (3개)
Yongjian Feng
2021년 8월 1일
Type
help ismember
in the matlab command line window to get quick help.
Basically the answer is the same length as the first input argument. When you have
ismember([a, b], otherArrary)
The answer is an array of length of 2 for this example. Each element in the returned array shows whether the corresponding elelment in the first import array is a member of the second input array.
댓글 수: 0
Image Analyst
2021년 8월 1일
You don't even need the admittedly confusing ismember() function. Assuming the matrices are regular numerical arrays (not cell arrays of strings), you can use simple logical indexing:
% Create sample data matrices m1 and m3:
m1 = [(1:9)', (11:19)']
m3 = [[0,2,0,4,0,6,0,8,0]', (11:19)']
% Find where column 1 of m1 matches column 1 of m3 and store in m2:
m2 = m1(:, 1) == m3(:, 1)
% Keep only rows in m1 and m2 that are in m3
rowsToKeep = m2;
m1 = m1(rowsToKeep, :)
m3 = m3(rowsToKeep, :)
You'll see:
m1 =
1 11
2 12
3 13
4 14
5 15
6 16
7 17
8 18
9 19
m3 =
0 11
2 12
0 13
4 14
0 15
6 16
0 17
8 18
0 19
m2 =
9×1 logical array
0
1
0
1
0
1
0
1
0
m1 =
2 12
4 14
6 16
8 18
m3 =
2 12
4 14
6 16
8 18
댓글 수: 0
Matt J
2021년 8월 1일
Wouldn't it just be,
mask = ismember(array2(:,1), array1) & ismember(array2(:,2), array3);
fn=@(z) z(mask,:);
array1=fn(array1);
array2=fn(array2);
array3=fn(array3);
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!