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!