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

조회 수: 53 (최근 30일)
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.

채택된 답변

Stephen23
Stephen23 2018년 10월 7일
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:

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by