Inserting non-evaluating MATLAB scripts into RMarkdown document

I have some MATLAB scripts that I run on some data prior to doing any analysis in R. Because of this, I'd like to display the relevant scripts (saved elsewhere in plain text files) in my RMarkdown document for the sake of reproducibility. I can copy and paste the code into my document and include it in a chunk like this:

'''{octave i_steps.m, eval=FALSE}
matlab script goes here...

(` not ')

which works fine, but if I make changes to the script, I'd like that to be reflected in my rmarkdown document (I will probably forget to copy/paste changes). So is there a way to import the matlab script (saved in a separate file) and include it in my rmarkdown file, preferably with code highlighting?


I'm pretty sure you could use a Lua filter to create a code-block element (see, but hopefully someone else will have a simpler suggestion.

Thanks for the tip mara. I'll have a think about it but it's definitely more involved than I would have hoped!

Code externalisation should work,

``` {r setup, include=FALSE}

followed by

```{octave test, eval=FALSE}

where the external file contains named chunks such as

# ---- test ----
x = [1:10];
plot(x, x)

Thanks baptiste. This is almost exactly what I need!

Just for others info, the inclusion of the # in the matlab file means matlab will return an error when running the script. Adding a % to the start (% # ---- test ----) does not work as it's omitted by knitr.

I can do something like the following at the top of the file, which is matlab's way of commenting out blocks of code:

# ---- test ----

This allows matlab to run the script and successfully prints the contents of the matlab file in my rmarkdown document, but unfortunately also prints %}.

I imagine there would be a way to change the chunk separator format but a cursory glance at ?read_chunk does not give an obvious hint. The format actually used to be different IIRC, so probably a small request if not currently available (it would make sense, based on this example).

Edit: actually, the regex is hard-coded,

.sep.label = "^(#|%|--)+\\s*(@knitr|----+)(.*?)-*\\s*$"
assignInNamespace(".sep.label", .sep.label, pos = "package:knitr")

Yihui might be open to a pull request to override the default.