MATLAB: Return only second output in anonymous function

anonymous functioncellcell arraycellfunMATLABmaxmultiple outputsmultiple return values

I need to get an index via max() and use this to get the corresponding element like in the following code:
data = complex(1:5,1:5);
[~,i] = max(abs(data));
res = real(data(i)):
Now, I want to do this for multiple datasets at once. Therefore I have a cell array of vectors. Below, you find a working version of what I am doing.
Is there an easier/faster/better way to do the following:
% test data
data = {complex(1:5,1:5) complex(6:10,6:10)};
% working example
fct = @(d) max(abs(d));
[~,idxs] = cellfun(fct, data, 'UniformOutput', false);
fct2 = @(idx, d) d(idx);
vals = cellfun(fct2, idxs, data, 'UniformOutput', false);
res = real([vals{:}]);

Best Answer

If you only want the indices, one possibility is to use the find function, returning only the index of the first maximum value it finds, matching the index returned by the second output of max. This produces the same result as your posted code:
% test data
data = {complex(1:5,1:5) complex(6:10,6:10)};
% working example
fct = @(d) find(abs(d) == max(abs(d)), 1, 'first');
idxs = cellfun(fct, data, 'Uni',0);
fct2 = @(idx, d) d(idx);
vals = cellfun(fct2, idxs, data, 'UniformOutput', false);
res = real([vals{:}]);
I’m also giving you a vote, because yours is an example of the way a Question is best posed. It’s one of the best I’ve seen.