Finding the value and index of the minimum value in a matrix, grouped by column values

I am trying to find the min value and index for each data group in the following matrix using matlab:

a=[0.3 1; 0.5 1; 0.2 1; 0.4 2 ; 0.43 2; 0.01 3; 0.3 3; 0.23 3]; 

Data is grouped by value in column 2. i.e. the first three lines refer to group 1, the next two lines refer to group 2, the last 3 lines refer to group 3.

thanks

0
source share
2 answers

Use accumarray with min to find the minimum values ​​for each group:

 v = accumarray( a(:,2), a(:,1), [], @min ) 

To get the minimum indices, build the lines:

 idx = find(ismember(a, [v, unique(a(:, 2))], 'rows')) 

Also, if you have m predefined groups, you can use (1:m)' instead of unique(...) .

+5
source

Another option:

  min(a(a(:,2)==1)) min(a(a(:,2)==2)) % etc... 

should work until the numbers in the second column are integers, otherwise the equality test will fail. If you use doubles, compare the difference between the values ​​with a (very) small tolerance (e.g. 1e-6).

+3
source

Source: https://habr.com/ru/post/1302503/


All Articles