extract from structure data with a field with the same value

I have a structure with several fields and I want to extract only the structure elements having the same value for a particular field.
For example:
A = struct('type', '', 'par1', 0, 'par2', 0);
A(1).type = 'type1';
A(1).par1 = 10;
A(1).par2 = 20;
A(2).type = 'type2';
A(2).par1 = 11;
A(2).par2 = 22;
A(3).type = 'type3';
A(3).par1 = 33;
A(3).par2 = 40;
.
.
.
A(10).type = 'type2';
A(10).par1 = -1;
A(10).par2 = -1;
I need to extract ONLY the elements with type = 'type1'; the only way I know to do this is to do a loop like this:
indx = [];
for ii = 1:length(A)
if strcmp(A(ii).type,'type1')
indx = [ind ii];
end
end
Actually, A is bigger than the example; is there an easier an faster way to do this?
Thank you

 Akzeptierte Antwort

Jan
Jan am 22 Jan. 2021
Bearbeitet: Jan am 22 Jan. 2021
match = strcmp({A.type}, 'type1'); % Logical indices
idx = find(match) % Indices
value = [A(match).par1] % Faster with logical indexing

5 Kommentare

Great! Thank you, Jan
..and If I want to do this for type = 'type1' and 'par1' = 10?
it works if I do:
match1 = strcmp({A.type}, 'type1');
idx = find(match1);
B = A(idx);
match2 = find(cell2mat({B.par1}) == 10);
value = [B(match2).par2];
but can I do this with only one 'match'?
Your apporach has some points for improvements:
idx = find(match1);
Index vectors are more expensive than addressing the elements by logical indexing. So prefer to use match1 directly and omit the find(). The find() for getting match2 is not needed also.
[B.par1] is nices and faster than cell2mat({B.par1}). Together:
match1 = strcmp({A.type}, 'type1');
B = A(match1);
match2 = ([B.par1] == 10);
value = [B(match2).par2];
Creating the partial copy B consumes a lot of ressources. It is cheaper to create the final index without this intermediate copy:
match = strcmp({A.type}, 'type1') & ([A.par1] == 10);
value = [A(match).par2]
Thank you Jan, I've guessed this solution, but I wasn't able to join these two conditions in the correct way...

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Produkte

Version

R2020b

Gefragt:

am 22 Jan. 2021

Kommentiert:

am 25 Jan. 2021

Community Treasure Hunt

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

Start Hunting!

Translated by