Index of maximum values in accumarray

Hello all,
I'm working with wind data that is measured every hour, the data is in the form of a matrix of 3 columns, the first is the date, the second is wind speed and the third is wind direction. I have created a code using accumarray in order to get the maximum daily value of wind speed. However I want to be able to get the corresponding wind direction for those maximum values, so for this, I need the indexes of the Maximum values.
I have tried the suggestion from here given by Walter. However, the resulting indexing shows a different result from the one I need (numerical example below):
My code is the following:
max_val = accumarray(c,wind(:,2),[],@nanmax);
max_index= accumarray(c,wind(:,2),[],@max_and_idx);
where:
function idx = max_and_idx(x)
[~,idx] = max(x);
end
the answer I get is:
max_val =[4.5 5.1 3.6 2.5 .....]
max_index=[16 15 15 12 .....]
I checked my data and 4.5 corresponds to position #15 in day 1, 5.1 corresponds to position #16 on day 2 and so on. What I want is the actual position of these numbers within the entire wind matrix. How can I fix this problem?

 Accepted Answer

Ameer Hamza
Ameer Hamza on 20 May 2018
Edited: Ameer Hamza on 22 May 2018
A better approach might be to use the splitapply to divide the data based on days. Then the better will be better organized and you can easily process for required results. For example
splitData = splitapply(@(x) {x}, wind(:,2:3), findgroups(c));
now you can search splitData to find the max value and the corresponding direction,
result = cellfun(@(x) x(x(:,1)==max(x(:,1)), :), splitData, , 'UniformOutput', 0);
the result will contain the maximum daily value and wind direction.

5 Comments

I agree that something like splitapply is a better choice here.
Dear all,
I have tried your suggestion, however I get the following error when I run the first line:
Error using splitapply (line 132)
Applying the function '@(x,y){[x,y]}' to the 1st group of data
generated the following error:
Not enough input arguments.
I changed the line to:
splitData = splitapply(@(x) {[x]}, wind(:,2:3), findgroups(c));
and it worked perfect: I have teh data divided in days, however when I run the second line I get:
Error using cellfun
Non-scalar in Uniform output, at index 1, output 1.
Set 'UniformOutput' to false.
I'm not very familiar with cellfun and splitapply so I don't know how to interpret these errors.
I made a mistake in splitapply(), i have corrected it now. Also made the required modification for cellfun(). Refer to the edited answer.
Thank you! This worked perfectly!
You are welcome.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!