Having defined the GNU/Octave cell array
dict =
{
[1,1] =
scalar structure containing the fields:
id = integers
vl = ... -2, -1, 0, 1, 2, ...
[1,2] =
scalar structure containing the fields:
id = positive integers
vl = 1, 2, 3, 4, ...
[1,3] =
scalar structure containing the fields:
id = negative integers
vl = -1, -2, -3, -4, ...
}
how to find (in Octave code, without looping!) the structs that have a given value in a field, say, those containing 'integer'
in the id
field, or -1
in the vl
field.
Update: The command would operate like find(dict,'vl','-1')
, returning 1, 3
, or 1 0 1
.
A possible implementation of the search function would look like:
function arrayvalues = findinfield(mycellarray, inputfield, outputfield, fieldvalue)
positions = ~cellfun(@isempty, regexp({[mycellarray{:}].(inputfield)}, fieldvalue));
arrayvalues = {[mycellarray{positions}].(outputfield)};
end
For an exact matching add ^
and $
to the beginning and end, respectively, of the regular expression.
Use cases:
findinfield(dict, "id", "vl", "integers")
ans =
{
[1,1] = ... -2, -1, 0, 1, 2, ...}
[1,2] = 1, 2, 3, 4, ...}
[1,3] = -1, -2, -3, -4, ...}
}
findinfield(dict, "id", "vl", "^integers$")
ans =
{
[1,1] = 1, 2, 3, 4, ...}
}
findinfield(dict, "id", "vl", "negative")
ans =
{
[1,1] = -1, -2, -3, -4, ...}
}