A question about ismember function

1 view (last 30 days)
Cantor Set
Cantor Set on 21 Oct 2021
Edited: Dave B on 21 Oct 2021
Suppose I have a matrix
M=[1 1 1; 1 1 1; 0 1 0; 5 5 5; 9 1 8; 5 5 5]; D=[1 1 1; 5 5 5; 9 1 8];
I=ismember(M,D,'rows');
I want to assign a number 1 to rows in M that are in D and 0 to rows in M that are not in D then, remove from M all the rows that crossponds to 1.
The answer is
I= [1 1 0 1 1 1]'
so I want to remove row in M that crossponds to 1 so I type
M(I,:)=[];
It gives M=[0 1 0]; which is the required.
My question is this correct for all problems of this kind?
what is the meaning of M(I,:) ? is not I a vector, how can we type M(vector,:) ? I mean I understand the command M(2,:) for example it means get me the second row in M but what is the meaning of M(vector,:)?

Accepted Answer

Dave B
Dave B on 21 Oct 2021
Edited: Dave B on 21 Oct 2021
Check out the documentation page here: https://www.mathworks.com/help/matlab/math/array-indexing.html (Indexing with Logical Values is about halfway down)
What this boils down to is you can index by row/column numbers: M(3,:) M([1 3 5],:) or by logicals (M([true;false;true;false;true],:))
M=magic(5)
M = 5×5
17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9
M(3,:)
ans = 1×5
4 6 13 20 22
M([1 3 5],:)
ans = 3×5
17 24 1 8 15 4 6 13 20 22 11 18 25 2 9
M([true;false;true;false;true],:)
ans = 3×5
17 24 1 8 15 4 6 13 20 22 11 18 25 2 9
Note that logical indexing is really really useful!
M(M(:,1)>10,:) % Rows of M where the first column is greater than 10
ans = 3×5
17 24 1 8 15 23 5 7 14 16 11 18 25 2 9
M(mod(M,2)==0)' % Even values in M
ans = 1×12
4 10 24 6 12 18 8 14 20 2 16 22
load sonnetsTable.mat
tbl.Word(tbl.Count>20)' % Words that occurred more than 20 times
ans = 1×22 cell array
{'Which'} {'beauty'} {'being'} {'every'} {'heart'} {'love'} {'might'} {'night'} {'praise'} {'shall'} {'should'} {'still'} {'sweet'} {'thee'} {'their'} {'thine'} {'those'} {'though'} {'where'} {'which'} {'world'} {'would'}
load patients
% mean of smokers, non smokers, and smokers with weight above the median
[mean(Diastolic(Smoker)) mean(Diastolic(~Smoker)) mean(Diastolic(Smoker & Weight>median(Weight)))]
ans = 1×3
89.9118 79.3788 90.3182

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by