Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a one-liner to find the minimum of unique entities from a matrix of multiple instances of each item?

Tags:

matrix

matlab

Say, I have a matrix A with 2 columns - column 1 contains item ID and column 2 contains its weight:

A = [
3   5
2   3
2   5
1   4
3   4
2   6
1   9
3   2 ];

I want the output as follows:

items = [
1   4
2   3
3   2];

The code I would write to do this would be:

items(:,1)=unique(A(:,1));
for i=1:size(items,1)
    temp=A(A(:,1)==items(i,1),:);
    items(i,2)=min(temp(:,2));
end

The items matrix is the required output here.

I was wondering if there is a one-liner code that does this in MATLAB.

like image 601
Kristada673 Avatar asked Sep 05 '16 05:09

Kristada673


3 Answers

assuming your item IDs are integers starting from one, you can use accumarray:

accumarray(a(:,1), a(:,2), [], @min);
like image 53
Shai Avatar answered Oct 17 '22 11:10

Shai


Use sortrows:

B = sortrows(A);
A_min = B([true; diff(B(:,1))~=0], :)

A_min =

     1     4
     2     3
     3     2

sortrows sorts the matrix in ascending order based on the first column, then the second. Use this new sorted vector and extract the first row, along with all rows where the first column changes (1, 2, 3).

[true; diff(B(:,1))~=0] is a vector containing boolean [true false false true ...]. true indicates where the elements in the first column change. This is used as a logical map to index the original array.

You should know that:

x = [1 2 3 4];
idx = [true false false true];
x(idx) = 
     1    4
like image 33
Stewie Griffin Avatar answered Oct 17 '22 11:10

Stewie Griffin


If you have an access to image processing toolbox you can do this:

[unique(A(:,1)),[regionprops(A(:,1),A(:,2),'MinIntensity').MinIntensity]']
like image 41
rahnema1 Avatar answered Oct 17 '22 11:10

rahnema1