Skip to content

Instantly share code, notes, and snippets.

@yihui
Created July 15, 2012 00:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yihui/3114112 to your computer and use it in GitHub Desktop.
Save yihui/3114112 to your computer and use it in GitHub Desktop.
Highlight Matlab code in knitr
\documentclass{article}
<<adjust-preamble, echo=FALSE, results='asis'>>=
if (opts_knit$get('use.highlight')) cat('\\def\\usehighlightdefs{1}\n')
@
\ifx\highlightexists\undefined
\newcommand{\hlstd}[1]{\textcolor[rgb]{0,0,0}{#1}}
\newcommand{\hlnum}[1]{\textcolor[rgb]{0.69,0.49,0}{#1}}
\newcommand{\hlesc}[1]{\textcolor[rgb]{1,0,1}{#1}}
\newcommand{\hlstr}[1]{\textcolor[rgb]{0.75,0.01,0.01}{#1}}
\newcommand{\hlpps}[1]{\textcolor[rgb]{0.51,0.51,0}{#1}}
\newcommand{\hlslc}[1]{\textcolor[rgb]{0.51,0.51,0.51}{\it{#1}}}
\newcommand{\hlcom}[1]{\textcolor[rgb]{0.51,0.51,0.51}{\it{#1}}}
\newcommand{\hlppc}[1]{\textcolor[rgb]{0,0.51,0}{#1}}
\newcommand{\hlopt}[1]{\textcolor[rgb]{0,0,0}{#1}}
\newcommand{\hllin}[1]{\textcolor[rgb]{0.33,0.33,0.33}{#1}}
\newcommand{\hlkwa}[1]{\textcolor[rgb]{0,0,0}{\bf{#1}}}
\newcommand{\hlkwb}[1]{\textcolor[rgb]{0,0.34,0.68}{#1}}
\newcommand{\hlkwc}[1]{\textcolor[rgb]{0,0,0}{\bf{#1}}}
\newcommand{\hlkwd}[1]{\textcolor[rgb]{0,0,0.51}{#1}}
\definecolor{bgcolor}{rgb}{0.88,0.92,0.93}
\else
\newcommand{\hlopt}[1]{\textcolor[rgb]{0,0,0}{#1}}
\fi
\begin{document}
Normal R chunks.
<<test-R>>=
1+1
rnorm(5)
@
Highlight matlab chunks.
<<test-matlab, engine='highlight', highlight.opts='-S matlab -O latex'>>=
function Y = kalmanM(pos)
dt=1;
%% Initialize state transition matrix
A=[ 1 0 dt 0 0 0;... % [x ]
0 1 0 dt 0 0;... % [y ]
0 0 1 0 dt 0;... % [Vx]
0 0 0 1 0 dt;... % [Vy]
0 0 0 0 1 0 ;... % [Ax]
0 0 0 0 0 1 ]; % [Ay]
% Initialize measurement matrix
H = [ 1 0 0 0 0 0; 0 1 0 0 0 0 ];
Q = eye(6);
R = 1000 * eye(2);
x_est = zeros(6, 1);
p_est = zeros(6, 6);
numPts = size(pos,1);
Y = zeros(numPts, 2);
for idx = 1:numPts
z = pos(idx, :)';
%% Predicted state and covariance
x_prd = A * x_est;
p_prd = A * p_est * A' + Q;
%% Estimation
S = H * p_prd' * H' + R;
B = H * p_prd';
klm_gain = (S \ B)';
%% Estimated state and covariance
x_est = x_prd + klm_gain * (z - H * x_prd);
p_est = p_prd - klm_gain * H * p_prd;
%% Compute the estimated measurements
Y(idx, :) = H * x_est;
end % of the function
end % of the function
@
\end{document}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment