Azzera filtri
Azzera filtri

Find indices in structure array for structures with field meeting a condition

55 visualizzazioni (ultimi 30 giorni)
Let's say I have an array of structures. Now I want to find the indices of the structures in the array for which two fields meet a certain condition. Is there a way to accomplish this without looping through the whole structure array? If I have vector A of numbers and simply want all indices for the numbers that are larger then 10 I could write: indices = A > 10; Something in this style just for structure - arrays is what I'm looking for.

Risposta accettata

Stephen23
Stephen23 il 7 Ott 2018
If the data in the fields can be concatenated together (i.e. have the same number of rows/columns/...) then you could use a comma-separated list to create one array, and use that array. For example:
>> S(1).a = 1;
>> S(2).a = 2;
>> S(3).a = 3;
>> idx = [S.a]>2
idx =
0 0 1
>> S(idx).a
ans = 3
Clearly you can do that for any fields. If the data cannot be concatenated together, or have sizes that would be ambiguous when joined together, then you will have to use a loop, even if implicitly inside cellfun. For example:
>> cellfun(@(v)any(v(:)>2),{S.a})
ans =
0 0 1
Read more here:

Più risposte (0)

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by