MATLAB: How to find the ‘n’th largest number and its position in a 4D array

arrayindexingmaximum

I am using the follwing code to find the maximum, but how do I find the 'n'th maximum?
ff =f(n+1, :, :, :);
[MAX,I] = max(ff(:));
dims = size(ff);
fmax = cell(size(dims));
[fmax{:}] = ind2sub(dims,I);

Best Answer

The standard answer applies. Break a problem that is too large for you to get your head around into small problems. Solve each sub-problem. Put it all together.
1. Sort the entire array (in descending order), when unrolled into a vector. Make sure you save the second argument from sort.
2. Take the index of the n'th element from that sort. That is just n.
3. Use that to then find the index of the n'th element in the original vector. Why do you think I told you to save the second output from sort?
4. Finally, use ind2sub, to find the location of that element as it would have been in the original array. And you clearly already know how to use ind2sub.
Each step is trivial.