How to find rows that contain value in another column vector

3 次查看(过去 30 天)
Let say I have matrix X as follows
X =
1 2 3
1 4 5
1 6 7
2 8 9
2 10 11
3 12 13
3 14 15
3 16 17
4 18 19
4 20 21
5 22 23
5 24 25
and column vector Y
Y=
2
4
5
So, I want to create a matrix where based on values in Y that has the same value of Column 1 of X
So,
Z=
2 8 9
2 10 11
4 18 19
4 20 21
5 22 23
5 24 25

回答(2 个)

KSSV
KSSV 2018-4-12
Read about ismemebr
X = [1 2 3
1 4 5
1 6 7
2 8 9
2 10 11
3 12 13
3 14 15
3 16 17
4 18 19
4 20 21
5 22 23
5 24 25];
Y=[2
4
5] ;
[ia,ib] = ismember(X(:,1),Y) ;
iwant = X(ia,:)

Walter Roberson
Walter Roberson 2018-4-12
Z = X(ismember(X(:,1), Y), :);
provided that the original order from X is acceptable.
That is, suppose that Y = [2; 5; 4], then would you need the Z to be in a different order?
If the X values had not happened to be in order by column 1, then would you still need the output to be in the same order as the Y values, or could they be in whatever order they were in in X ?

类别

Help CenterFile Exchange 中查找有关 Get Started with MATLAB 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by