Finding rows of minimum valueS by group

2 views (last 30 days)
Afak Nazim
Afak Nazim on 14 Dec 2022
Edited: Voss on 14 Dec 2022
I want to select the rows with the lowest values (more than one) by group
In the following for each date3( col:2), I want to select the rowS with the lowest TimeToMaturity(6)

Answers (2)

KSSV
KSSV on 14 Dec 2022
Let date2 and TimeToMaturity be your two column arrays.
[c,ia,ib] = unique(date2) ;
N = length(c) ;
iwant = zeros(N,1) ;
for i = 1:N
iwant(i) = min(TimeToMaturity(ib==i)) ;
end
[c iwant]
  4 Comments
Afak Nazim
Afak Nazim on 14 Dec 2022
idx is an integer with a value of 1. Not sure this qualifies as an index..
KSSV
KSSV on 14 Dec 2022
Index should be a integer...it shall qualify...

Sign in to comment.


Voss
Voss on 14 Dec 2022
Edited: Voss on 14 Dec 2022
Some data like your date3 and TimeToMaturity columns (just using 1, 2, 3, 4 for date here):
date = reshape(repmat(1:4,5,1),[],1);
time_to_maturity = randi(100,20,1);
disp([date time_to_maturity]);
1 86 1 64 1 44 1 18 1 60 2 37 2 72 2 98 2 60 2 3 3 62 3 22 3 22 3 82 3 67 4 49 4 70 4 39 4 73 4 62
Now find the minimum time_to_maturity for each date and the row where it occurs:
[ud,~,jj] = unique(date);
N = numel(ud);
val = zeros(N,1);
row = zeros(N,1);
for ii = 1:N
group_idx = find(jj == ii);
[val(ii),temp_idx] = min(time_to_maturity(group_idx));
row(ii) = group_idx(temp_idx);
end
fprintf('Date %d: minimum TimeToMaturity is %02d, which occurs in row %02d\n',[ud val row].');
Date 1: minimum TimeToMaturity is 18, which occurs in row 04 Date 2: minimum TimeToMaturity is 03, which occurs in row 10 Date 3: minimum TimeToMaturity is 22, which occurs in row 12 Date 4: minimum TimeToMaturity is 39, which occurs in row 18

Categories

Find more on Resizing and Reshaping 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!