필터 지우기
필터 지우기

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

조회 수: 1 (최근 30일)
Emma Kuttler
Emma Kuttler 2022년 3월 22일
편집: Voss 2022년 3월 24일
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