Find a match in a structure array using arrayfun
17 次查看(过去 30 天)
显示 更早的评论
Hi there,
I have some data stored in a structure array s, with the following fields: s.Month, s.Day, s.Hour and s.Data. The structure array has the size of 1x123, i.e.a time series of 123 time steps.
I try to find a certain set within the structure array, matching the date, say 08/21 00 UTC.
My idea was:
m = 8; d = 21; h = 0;
index = find( arrayfun(@(x) x.Month==m & x.Day==d & x.Hour==h, s) );
data = s(index).Data;
But the result of arrayfun() is an empty matrix. (I know that the index must be 81.)
What actually works is:
find( arrayfun(@(x) x.Month==m,s) & ...
arrayfun(@(x) x.Day==d,s) & ...
arrayfun(@(x) x.Hour==h,s) )
ans =
81
My question is: why does the first option not work ?
Thank you for an answer.
3 个评论
dpb
2014-6-5
编辑:dpb
2014-6-5
If it walks like a duck, quacks like a duck, plays golf like the AFLAC duck, ... :)
OKAY, I always start out thinking I've just got a comment then something happens--like the realization of the [] to build the arrays above was after I was already to sign off having simply noted his solution worked for me. I don't follow what didn't in his case, yet, however...
I'd noticed you'd been pinging a bunch but I'm not sure I'll live long enough to get to the privilege level of any significance... :)
The only thing I miss as structured is that sometimes it would be good to re-edit a submission but it takes excessive amount of time already. What I really miss that doesn't seem to exist at all is for feedback from the privileged be considered in updating the forum. It wouldn't be necessary to have to re-edit so much code if the default weren't wordwrap and a few other details like that...there is so much wasted effort in cleaning up happening even as it is and not a tenth of what should gets done.
Image Analyst
2014-6-5
You're not far from 2000 when you'll be able to edit posts of others. I'll help by giving you 2 points per vote so you'll be there shortly.
采纳的回答
dpb
2014-6-5
编辑:dpb
2014-6-5
Not certain; it did for a small sample case here...but you can write it w/o arrayfun as
ix=find([s.Month]==m & [s.Day]==d & [s.Hour]==h);
making the arrays from the struct.
ADDENDUM
Or, add a datenum value as another field and make your search on the single variable might be faster searching and certainly less complicated to build the search pattern I think. It's certainly much simpler to do ranges that way.
2 个评论
dpb
2014-6-6
Figured had to be something of the sort; glad you found it.
Interesting that there's that large a speed difference...I hadn't timed it as just used a very short handmade test vector to verify syntax.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!