Clear Filters
Clear Filters

Function that returns index of first occurrence of largest value for each column of matrix

3 views (last 30 days)
I would like to write a function that returns the index of the first occurrence of the largest value in each column of a matrix. Ideally it would also have the flexibility to specify the row or the columns as the search direction, and/or could work for N-dimensional matrices.
I thought that the following would work:
function [ maxind ] = findmax( indata,k,varargin )
maxind = find(indata == max(indata),k,varargin(:));
But, when I pass a matrix into the function I get the following error:
maxind = findmax(indata,1,'first')
Undefined function 'find' for input arguments of type 'cell'.
Error in findmax (line 6)
maxind = find(indata == max(indata),k,varargin(:));

Accepted Answer

Cedric on 11 Sep 2015
Edited: Cedric on 11 Sep 2015
Another solution, almost trivial, is just to use the second output of MAX, which is the index of the first occurrence, and to flip along dim if there is a 3rd input arg. not starting with 'f'.
function maxInds = findMax( A, dim, direction )
if nargin < 2
dim = 1 ;
if nargin < 3
direction = 'f' ;
if direction(1) == 'f'
[~, maxInds] = max( A, [], dim ) ;
[~, maxInds] = max( flip( A, dim ), [], dim ) ;
maxInds = size( A, dim ) + 1 - maxInds ;

More Answers (0)


Find more on Creating and Concatenating Matrices in Help Center and File Exchange


Community Treasure Hunt

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

Start Hunting!