Filter löschen
Filter löschen

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

1 Ansicht (letzte 30 Tage)
Emma Kuttler
Emma Kuttler am 22 Mär. 2022
Bearbeitet: Voss am 24 Mär. 2022
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]

Antworten (1)

Voss
Voss am 22 Mär. 2022
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 Kommentare
Emma Kuttler
Emma Kuttler am 24 Mär. 2022
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 am 24 Mär. 2022
Bearbeitet: Voss am 24 Mär. 2022
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

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Shifting and Sorting Matrices finden Sie in Help Center und File Exchange

Produkte


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by