Finding rows of minimum valueS by group

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)

Réponses (2)

KSSV
KSSV le 14 Déc 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 commentaires

Afak Nazim
Afak Nazim le 14 Déc 2022
Thank you for your reply. However it does not solve the problem. It doesnt select the rows, it just gives an array of minimum values
iwant(i) = min(TimeToMaturity(ib==i)) ;
The above line gives index, if you modify it to:
[iwant(i),idx] = min(TimeToMaturity(ib==i)) ;
You have the index in hand...you can pick it. REad the documentation of min
Afak Nazim
Afak Nazim le 14 Déc 2022
idx is an integer with a value of 1. Not sure this qualifies as an index..
KSSV
KSSV le 14 Déc 2022
Index should be a integer...it shall qualify...

Connectez-vous pour commenter.

Voss
Voss le 14 Déc 2022
Modifié(e) : Voss le 14 Déc 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

Catégories

Question posée :

le 14 Déc 2022

Modifié(e) :

le 14 Déc 2022

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by