Find minimum value within struct

17 次查看(过去 30 天)
Hi
I'm trying to determine the minimum value within a struct. I have a data struct with subfields which are timestamped. I'd like to find the smallest time, then reference all the other data accordingly.
example of the data:
  • data.val1.time = something
  • data.val2.time = something else
  • .
  • .
  • data.valN.time = something else
I can think of a brute force way of doing it, but I'm thinking that there should be a nicer way.
anyone have any ideas?
  1 个评论
Jan
Jan 2011-8-3
Are "val1", "val2", ... the real field names? Then I strongly recommend to use an array instead: val(1), val(2), ... This will make the conversion of the subfield .time much easier.

请先登录,再进行评论。

采纳的回答

Friedrich
Friedrich 2011-8-3
Hi,
I think you have to convert from a structure to an array. Maybe like this:
>> data.a = 1;
>> data.b = 2;
>> data.c = 3;
>> min(cell2mat(struct2cell(data)))
  2 个评论
Friedrich
Friedrich 2011-8-3
for your struct more ugly:
min(cell2mat(struct2cell(cell2mat(struct2cell(data)))))
Jan
Jan 2011-8-3
I assume this is faster:
C = struct2cell(data);
min([C{:}])

请先登录,再进行评论。

更多回答(1 个)

Sean de Wolski
Sean de Wolski 2011-8-3
min(structfun(@min,data));
is significantly faster on my machine. Conversions to and from cells take awhile.
  1 个评论
Jan
Jan 2011-8-3
STRUCT2CELL is surprisingly fast, because the underlying representation is almost equivalent: Only the list of field names is different.
But CELL2MAT is slow, because it does not pre-allocate sufficiently. Anyhow, for 3 or 100 fields the speed will not be too important.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by