How to select rows of matrix based on other matrix column?

1 次查看(过去 30 天)
Hi, I have a single column matrix called "nodes" and a larger matrix with many columns called "arcs". If values from "nodes" appear in both of the first two columns of "arcs", I want to return that row from "arcs" and put it in a new matrix. If one or both of the values in the first two columns of "arcs" does not appear in "nodes", do not return that row.
For example, if these are the matrices nodes and arcs, I want to produce "arcssmall"
nodes = [1
2
4
6
9
11]
arcs = [1 2 0 1 4
1 3 9 8 7
2 1 8 3 0.5
4 11 9 0 0
6 9 5 5 5
5 6 1 2 3
9 1 0 0 0
7 8 6 7 7]
arcssmall = [1 2 0 1 4
2 1 8 3 0.5
4 11 9 0 0
6 9 5 5 5
9 1 0 0 0]

回答(1 个)

Voss
Voss 2022-3-22
nodes = [1
2
4
6
9
11];
arcs = [1 2 0 1 4
1 3 9 8 7
2 1 8 3 0.5
4 11 9 0 0
6 9 5 5 5
5 6 1 2 3
9 1 0 0 0
7 8 6 7 7];
arcssmall = arcs(all(ismember(arcs(:,[1 2]),nodes),2),:)
arcssmall = 5×5
1.0000 2.0000 0 1.0000 4.0000 2.0000 1.0000 8.0000 3.0000 0.5000 4.0000 11.0000 9.0000 0 0 6.0000 9.0000 5.0000 5.0000 5.0000 9.0000 1.0000 0 0 0
  2 个评论
Emma Kuttler
Emma Kuttler 2022-3-24
Thanks! How would I change the script so that I was only checking in the first column of arcs to see if there was a match for a value in nodes?
Voss
Voss 2022-3-24
编辑:Voss 2022-3-24
nodes = [1
2
4
6
9
11];
arcs = [1 2 0 1 4
1 3 9 8 7
2 1 8 3 0.5
4 11 9 0 0
6 9 5 5 5
5 6 1 2 3
9 1 0 0 0
7 8 6 7 7];
% arcssmall = arcs(all(ismember(arcs(:,[1 2]),nodes),2),:)
arcssmall = arcs(ismember(arcs(:,1),nodes),:) % change [1 2] to just 1, and no need to use all(__,2) in this case
arcssmall = 6×5
1.0000 2.0000 0 1.0000 4.0000 1.0000 3.0000 9.0000 8.0000 7.0000 2.0000 1.0000 8.0000 3.0000 0.5000 4.0000 11.0000 9.0000 0 0 6.0000 9.0000 5.0000 5.0000 5.0000 9.0000 1.0000 0 0 0

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by