how to find the immediate date before in one column based on another column using find function?

1 回表示 (過去 30 日間)
i have 2 columns with double type.
first column is 80 x 1 with double type
second column is 238 X 1 with double type.
we need to find the immediate date before the date present in Column 1. column 1 has date as 20020102 we need to find date which date is immediate before this date . in this case for 20020201(column 1) the immediate date before is 20011231(column 2).

採用された回答

per isakson
per isakson 2021 年 10 月 30 日
編集済み: per isakson 2021 年 10 月 30 日
Assumptions:
  • the two column vectors are sorted
  • a specific date in the first vector may exist in the second vector
  • more than one date in the first vector may have the same "immediate date before" in the second vector
Try this example with your data
%%
c1 = [ 20020102; 20020107; 20020115; 20020129 ];
c2 = [ 20020101; 20020103; 20020104; 20020106; 20020115; 20020128; 20020130; 20020131];
%%
tic
c = [ c1+eps(1e9); c2 ];
[b,ixs] = sort( c );
for jj = 1 : numel(c1)
ix = find(ixs==jj)-1;
fprintf( '%9d,%9d\n', round(c1(jj)), b(ix) );
end
20020102, 20020101 20020107, 20020106 20020115, 20020115 20020129, 20020128
toc
Elapsed time is 0.074653 seconds.
%%
tic
for jj = 1 : numel(c1)
ix = find( c2<=c1(jj), 1,'last');
fprintf( '%9d,%9d\n', c1(jj), c2(ix) );
end
20020102, 20020101 20020107, 20020106 20020115, 20020115 20020129, 20020128
toc
Elapsed time is 0.008355 seconds.
%%
tic
ix = interp1( c2, (1:8), c1, 'previous' );
c2(ix)
ans = 4×1
20020101 20020106 20020115 20020128
toc
Elapsed time is 0.452508 seconds.
There is a bug in the first solution.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCalendar についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by