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.
assuming your item IDs are integers starting from one, you can use accumarray
:
accumarray(a(:,1), a(:,2), [], @min);
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
If you have an access to image processing toolbox you can do this:
[unique(A(:,1)),[regionprops(A(:,1),A(:,2),'MinIntensity').MinIntensity]']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With