Reputation: 3086
I need to find indices in cell array of structs. For example, given:
arr{1}.id = 015
arr{2}.id = 015
arr{3}.id = 015
arr{4}.id = 015
arr{5}.id = 037
arr{6}.id = 037
arr{7}.id = 037
arr{8}.id = 037
arr{9}.id = 037
arr{10}.id = 037
arr{11}.id = 040
arr{12}.id = 040
...
I need to find indices which correspond to id=037 only (indx = [5 6 7 8 9])
Is there a simple matlabish solution, without using loops and searching for each individual element?
Upvotes: 1
Views: 254
Reputation: 36710
Vectorisation is the primary tool to avoid loops and write fast code. It can be used when applying the same operation to many elements of the same kind. While in this case you want the same operation, the elements are different. Using a loop (which cellfun is) is the only possibility.
>> find(cellfun(@(x)(x.id),arr)==37)
ans =
5 6 7 8 9 10
With the application you described I expect you will repetedly use this line, to have at least clean code I recommend to use a function
>> cellfield=@(data,field)(cellfun(@(x)(x.(field)),data))
cellfield =
@(data,field)(cellfun(@(x)(x.(field)),data))
>> cellfield(arr,'id')
ans =
Columns 1 through 8
15 15 15 15 37 37 37 37
Columns 9 through 12
37 37 40 40
Upvotes: 1