How can I find the minimum value corresponding to certain corresponding values?

1 view (last 30 days)
I'm still quite new to matlab and was hoping someone might be able to help me.
I have data related to every day of the year since late 1978. I've organised this into two 11221x1 vectors, one with the year (1978-2013) and one with the corresponding value (3.3-16.6).
I want two 36x1 vectors, one with each year and one with the corresponding minimum value relating to that year.
Simple answers please, I am at the bottom of a steep learning curve!
Thanks

Accepted Answer

Guillaume
Guillaume on 6 Feb 2015
Edited: Guillaume on 6 Feb 2015
unique will give the unique years, and its third return value which row they come from. accumarray will allow you to use that third return value of unique to find the minimum of the corresponding values.
demoyear = [1978 1979 1980 1978 1978 1980 1979]';
demodata = [2.1 4.2 3.3 1.4 8.5 7.6 6.7]';
[years, ~, location] = unique(demoyear);
minyear = accumarray(location, demodata, [], @min);
result = table(years, minyear, 'VariableNames', {'year', 'minimum'})
accumarray is a bit difficult to understand to start with. It works in two steps. First, it creates bins to put the values of demodata. The corresponding value of location tells it which bin to put a demodata value in. Once it's gone through all the values / locations, it then applies the function (min) to each bin.
If you look at location in my example, it's [1 2 3 1 1 3 2]'. The first value of location is 1, so the first value of demodata goes into bin 1, the 2nd value of location is 2 so the 2nd value of demodata goes into bin 2, the 4th value of location is 4, so the 4th value of demodata goes into bin 1 (together with the first value), etc. accumarray then return the minimum of each bin (because the function I give it is @min).

More Answers (0)

Community Treasure Hunt

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

Start Hunting!