How to call vector in matrix with condition

3 ビュー (過去 30 日間)
ha ha
ha ha 2018 年 12 月 14 日
コメント済み: Jan 2018 年 12 月 14 日
Let's say:
A=[7 2 3 50;4 5 6 15;1 8 9 20;1 1 1 30]
A= 7 2 3 50
4 5 6 15
1 8 9 20
1 9 8 30
B=[1; 7]
B=[1
7]
Question: I wanna call only vector in column 4 of matrix A with the condition is: the value of matrix B have the same value of vector in 1st column of matrix A?
I hope the result like that:
result=[20; 30;50]
result=[20
30
50]
i try :
result=A(ismember(A(:,1),B,'rows'),4);
But, result=[50; 20;30]% it is not in order of vector in matrix B ????

採用された回答

Bruno Luong
Bruno Luong 2018 年 12 月 14 日
[tf,loc] = ismember(A(:,1),B);
r = sortrows([loc(tf),A(tf,4)],1);
r(:,2)
ans =
20
30
50

その他の回答 (2 件)

Jan
Jan 2018 年 12 月 14 日
[m, loc] = ismember(A(:,1), B);
R = A(m,4);
[~, q] = sort(loc(m));
R = R(q)
  1 件のコメント
Jan
Jan 2018 年 12 月 14 日
Sorting loc(m) and using the index is exactly what happens inside sortrows([loc(m), A(m,4)], 1), so this answer is almost identical to Bruno's.

サインインしてコメントする。


KSSV
KSSV 2018 年 12 月 14 日
編集済み: KSSV 2018 年 12 月 14 日
k = A(A(:,1)==B(1),4)
l = A(A(:,1)==B(2),4)
Or
[idx,ia] = ismember(A(:,1),B)
iwant = A(idx,4)
  1 件のコメント
ha ha
ha ha 2018 年 12 月 14 日
編集済み: ha ha 2018 年 12 月 14 日
Thanks @KSSV
But, i follow your code, and the result is :
result=[50; 20;30]% it is not in order of vector in matrix B ????
It is NOT what I want(bz it is not in order).

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by