bio_img_finance

Quantitative Finance

Investment Management, Risk Management, Algorithmic Trading, Econometric Modeling, Pricing and Insurance

Bring R Data and Model Results into MATLAB

If you estimate models in R and use MATLAB for forecasting or reporting, you can import the saved data and results directly.

MATLAB Reader for R Data Files reads .rds, .rda, and .RData files. It converts R data frames to MATLAB tables and named workspaces to dictionaries. Tables with dates can also be imported as timetables. Import runs entirely in MATLAB.

The worked example below uses public unemployment data to show how to reproduce an R forecast in MATLAB.

Install the Reader

To install from MATLAB Central, open Add-Ons on the MATLAB Home tab. Search for MATLAB Reader for R Data Files, select the reader, and follow the installation prompts.

Alternatively, download rDataReader.mltbx from the latest release and open it in MATLAB, or run:

matlab.addons.install("rDataReader.mltbx")

The MATLAB examples require only MATLAB R2025a or later and the reader. R is used to generate the input files.

If you downloaded the source code, run this from the repository folder:

addpath(fullfile(pwd, "tbx", "rdatareader"))

Read an Economic Dataset

Start with OECDGrowth, a public dataset in the Applied Econometrics with R (AER) package. It contains 22 observations and six variables for growth regressions.

url = "https://raw.githubusercontent.com/cran/AER/master/data/OECDGrowth.rda";
options = weboptions(Timeout=30, ContentReader=@rdata2table);
T = webread(url, options);
head(T)

webread downloads the R file, and rdata2table returns a MATLAB table. Its columns are gdp85, gdp60, invest, school, randd, and popgrowth.

To read the same file from your computer, use T = rdata2table(“OECDGrowth.rda”). Use readrdata to import a workspace containing several named objects.

Estimate a Model in R

USMacroSW, also from AER, contains quarterly data from 1957 Q1 to 2005 Q1. The dataset accompanies Stock and Watson’s Introduction to Econometrics.

Use the unemployment rate to fit a first-order autoregression:

ut = a + ϕut−1 + ϵt.

Here t indexes quarters; ut is the unemployment rate in percent; and ut−1 is its value in the previous quarter. The intercept a is measured in percentage points, ϕ is a dimensionless lag coefficient, and ϵt is the one-quarter innovation, also in percentage points, assumed to have conditional mean zero.

The estimation sample ends in 1995 Q4. Forecasts cover 1996 Q1 to 2005 Q1, each using the previous quarter’s observed unemployment rate. The coefficients stay fixed.

Create a data frame with unemployment, its lag, and a training flag. Use the first day of each quarter as its date label.

url <- paste0(
    "https://raw.githubusercontent.com/cran/AER/",
    "342a1842306047a279e47026c3800718221a3b2c/data/USMacroSW.rda"
)
download.file(url, "USMacroSW.rda", mode = "wb")
load("USMacroSW.rda")

date <- seq(as.Date("1957-01-01"), by = "quarter",
            length.out = nrow(USMacroSW))
u <- as.numeric(USMacroSW[, "unemp"])
model_data <- data.frame(
    Date = date[-1],
    Unemployment = u[-1],
    LagUnemployment = head(u, -1)
)
model_data$Training <- model_data$Date < as.Date("1996-01-01")

Fit the model by ordinary least squares and save the data and coefficients:

fit <- lm(Unemployment ~ LagUnemployment,
          data = model_data, subset = Training)
model_data$RForecast <- as.numeric(predict(fit, newdata = model_data))
coefficients <- data.frame(
    Term = c("Intercept", "LagUnemployment"),
    Estimate = unname(coef(fit))
)

saveRDS(model_data, "unemployment.rds", compress = "gzip", version = 3)
save(coefficients, file = "baseline.RData",
     compress = "gzip", version = 3)

The files contain the dated observations, training flags, reference forecasts, and estimated coefficients. MATLAB will use these saved values in the next step.

Import the R Results into MATLAB

In MATLAB, put unemployment.rds and baseline.RData in the current folder and run:

TT = rdata2table("unemployment.rds", ...
    OutputType="timetable", ...
    RowTimes="Date");

baseline = readrdata("baseline.RData");
coefficients = baseline{"coefficients"};
head(TT)

The Date column becomes the timetable’s row times. The other columns contain unemployment, its lag, the training flag, and the R forecast. Creating the lag leaves 192 observations: 155 for estimation and 37 for evaluation.

The first eight quarters of the unemployment timetable imported from R, with date, unemployment, lag, training, and forecast columns.
First eight rows imported from R, displayed in a MATLAB table. Numeric values are shown to four decimal places.

readrdata returns a dictionary, with each saved R object available by its original name. baseline{“coefficients”} retrieves the coefficient table. Named R lists also become dictionaries.

You can also inspect the imported column types and missing-value metadata:

variableMetadata = TT.Properties.CustomProperties.RDataVariableMetadata;
timeMetadata = TT.Properties.CustomProperties.RDataRowTimeMetadata;
variableMetadata(:, ["VariableName", "RType", "MissingMask"])

Use MissingMask to identify missing values in each variable. The reader documentation explains the metadata fields.

Compare the Forecasts

Use the imported coefficients to calculate the same one-quarter-ahead forecasts:

b = coefficients.Estimate;
matlabForecast = b(1) + b(2)*TT.LagUnemployment;
evaluation = ~TT.Training;

maxDifference = max(abs( ...
    matlabForecast(evaluation) - TT.RForecast(evaluation)));
assert(maxDifference < 1e-12)

The 37 forecasts calculated in MATLAB match those saved by R.

Observed unemployment and the R and MATLAB forecasts from 1996 to 2005, with a lower panel showing the forecast difference.
R forecasts (blue line) and forecasts calculated in MATLAB (green circles). The lower panel shows the difference. Data: AER USMacroSW; Stock and Watson (2007).

You can also estimate the coefficients directly in MATLAB:

X = [ones(height(TT),1), TT.LagUnemployment];
bMatlab = X(TT.Training,:) \ TT.Unemployment(TT.Training);
maxCoefficientDifference = max(abs(bMatlab - b));
assert(maxCoefficientDifference < 1e-12)

The coefficients estimated in MATLAB match those from R.

Continue the Analysis in MATLAB

You can use the same approach to pass estimates from R into an existing MATLAB forecasting model or reporting script. The files could hold coefficients, posterior draws, or forecast series from your own R analysis.

Saved R results also give you a reference when re-estimating a model in MATLAB. For other time series models, Econometrics Toolbox provides estimation, forecasting, and diagnostic tools.

Try the Getting Started guide or download the R and MATLAB example to run the code from this post.

|
  • print

Comments

To leave a comment, please click here to sign in to your MathWorks Account or create a new one.