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

2 visualizzazioni (ultimi 30 giorni)
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).

Risposta accettata

per isakson
per isakson il 30 Ott 2021
Modificato: per isakson il 30 Ott 2021
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.

Più risposte (0)

Categorie

Scopri di più su Programming in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by