Borrar filtros
Borrar filtros

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

1 visualización (últimos 30 días)
Emma Kuttler
Emma Kuttler el 22 de Mzo. de 2022
Editada: Voss el 24 de Mzo. de 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]

Respuestas (1)

Voss
Voss el 22 de Mzo. de 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 comentarios
Emma Kuttler
Emma Kuttler el 24 de Mzo. de 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 el 24 de Mzo. de 2022
Editada: Voss el 24 de Mzo. de 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

Iniciar sesión para comentar.

Categorías

Más información sobre Shifting and Sorting Matrices en Help Center y File Exchange.

Productos


Versión

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by