- 2nd: the value 2 is a member of both "Group 1" and "Group 2", why does the output only show "Group 1"?
- 3rd: the value 3 is only a member of "Group 2", why does the output show "Group 1"?
Conditionally select from array of struct by membership of a list in struct element
8 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Rick Nickle
el 22 de En. de 2021
Comentada: Rick Nickle
el 22 de En. de 2021
Here's my array of structs:
X(1).Members=[1 2]
X(1).Name="Group 1"
X(2).Members=[2 3]
X(2).Name="Group 2"
Here's the conditional selection form I'm familiar with. I'm hoping there's a better way to express this:
A=[X(ismember(1,[X.Members])).Name]
A = "Group 1"
A=[X(ismember(2,[X.Members])).Name]
A = "Group 1"
A=[X(ismember(3,[X.Members])).Name]
A = "Group 1"
A=[X(ismember(4,[X.Members])).Name]
A = []
Since the 'ismember' operator returns a logical, the expression as formed returns the index of X to 0 or 1.
I would like to apply an expression to X and return each struct in X where a member is in the list of Members in the struct.
1 comentario
Stephen23
el 22 de En. de 2021
Editada: Stephen23
el 22 de En. de 2021
The 2nd and 3rd example outputs seem a bit strange:
Respuesta aceptada
Stephen23
el 22 de En. de 2021
Editada: Stephen23
el 22 de En. de 2021
X(1).Members = [1,2];
X(1).Name = 'Group 1';
X(2).Members = [2,3];
X(2).Name = 'Group 2';
F = @(n)arrayfun(@(s)any(s.Members==n),X);
F(1)
F(2)
F(3)
F(4)
If you really want to use ismember, replace the anonymous function with this:
@(s)ismember(n,s.Members)
0 comentarios
Más respuestas (1)
Ver también
Categorías
Más información sobre Structures en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!