3
votes

I have a 35 x 24 matrix of numbers. Each of the 35 rows obviously has a maximum value. I'm trying to write a short piece of code which determines which of the 24 columns contains the most of these max values. The catch is that no loops are allowed.

For example if the maximum values for 30 different rows all happened to lie in column 7 then I would want MATLAB to return the answer 7 since this is the column with the most max row values.

2

2 Answers

2
votes

If the values in each row are unique, we can simply use the second output of max combined with the mode to figure out which column contains the maximum of each row most often.

% Find the column which contains the maximum value
[~, column] = max(data, [], 2);
result = mod(column);   

However, below is a more general solution that allows a given maximum value to occur multiple times per row.

maximaPerColumn = sum(bsxfun(@eq, data, max(data, [], 2)), 1);
result = find(maximaPerColumn == max(maximaPerColumn));

Explanation

First we want compute the maximum value for each row (maximum across columns, dimension 2).

rowMaxima = max(data, [], 2);

Then we want to replace each row with a 1 if the value is equal to the max of that row and 0 otherwise. We can easily do this using bsxfun.

isMaxOfRow = bsxfun(@eq, data, rowMaxima);

Then we want to figure out how many times a given column contains a max of a row. We can simply sum down the columns to get this.

maximaPerColumn = sum(isMaxOfRow, 1);

Now we want to find the column which contained the maximum number of maxima. We use find due to the fact that more than one column could contain the same number of maxima.

result = find(maximaPerColumn == max(maximaPerColumn));
0
votes

I think you are looking for this:

sum(A==max(A,[],2))

Example:

A = [1 1 1; 
2 2 2; 
3 2 1]

M = sum(A==max(A,[],2))

Returns:

[3 2 2]

The first column has the most row wise max values. You could use find to identify this column.

find(M==max(M))