Finding rows of minimum valueS by group

2 ビュー (過去 30 日間)
Afak Nazim
Afak Nazim 2022 年 12 月 14 日
編集済み: Voss 2022 年 12 月 14 日
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)

回答 (2 件)

KSSV
KSSV 2022 年 12 月 14 日
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 件のコメント
Afak Nazim
Afak Nazim 2022 年 12 月 14 日
idx is an integer with a value of 1. Not sure this qualifies as an index..
KSSV
KSSV 2022 年 12 月 14 日
Index should be a integer...it shall qualify...

サインインしてコメントする。


Voss
Voss 2022 年 12 月 14 日
編集済み: Voss 2022 年 12 月 14 日
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

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by