MATLAB: Refer to the value of a variable referenced by the value of another variable

MATLAB

Suppose I have a table
date n_visitor n_reference_visitor
------------------------------------
January-1-2020 100
January-2-2020 50
January-3-2020 25
I want to do something like
if date is before January-2-2020, then the value of a variable "n_reference_visitor= the value of n_reference_visitor at January-2-2020
That is, I want to have
date visitor n_reference_visitor
--------------------------------------------------------------
January-1-2020 100 100 50
January-2-2020 50 50 50
January-3-2020 25 25
Please advise.

Best Answer

datetime() supports several of the operators supported by numeric types, including comparison operators. For example, check the following code
dts = datetime(2020,1,1)+(0:2);
T = table(dts.', [100; 50; 25], [0; 0; 0], 'VariableNames', {'date', 'n_visitor', 'n_reference_visitor'});
ref_date = datetime(2020,1,2); % January-2-2020
val = T.n_visitor(T.date==ref_date);
T.n_reference_visitor(T.date<=ref_date) = val;