MATLAB: Need 3rd dimension indicies for calling values.

multidimensional indexing

I am trying to find the value in one three dimensional array that corresponds to the location of a maximum in another.
In my case I have a variable called "N2s" and "avg_dye03". both of these have the same dimension of 340x291x20.
I first found the indicies of the third dimension maximum of N2s via the following…
index=find(max(N2s,[],3));
I then use index to call the values of avg_dye03 that correspond to the third dimensional maximum of N2s via…
avg_dye03(index)
My issue is that this returns a 1 dimension array with dimensions 98935×1.
I want the values of avg_dye03 that correspond to the third dimension maximum of N2s to have dimensions of 340x291x1 (same as if I just did max(N2s,[],3)).
I've tried using ind2sub, but the I constantly get a value of 1 for the third dimensional index (1st and 2nd dimensional indicies seem ok). Further more, generating a 340x291x1 matrix using the three indicies from ind2sub would require a tedious set of for loops that I haven't got patience or resources to run.
Any help with this would be greatly appreciated.

Best Answer

m = size(N2s,1);
n = size(N2s,2);
[~,x] = max(N2s,[],3); % 3rd dimension indexes of the max locations
y = (1:m*n)' + (x(:)-1)*(m*n); % linear index of these locations in full array
result = reshape(avg_dye03(y),m,n); % use linear indexing, then reshape result