Latex 中插入 Matlab 代码

news2025/1/22 15:07:08

这篇文章将介绍如何在 Latex 排版过程中添加 Matlab 代码

功能效果
主要有如下排版功能:

  • 语法高亮
  • 自动添加边框
  • 自动添加行号

先上图,大家感受一下效果:
在这里插入图片描述
而实现这些只需要一行代码加一个包!

  1. 插入代码块
\usepackage{listings}
\usepackage[framed,numbered,autolinebreaks,useliterate]{mcode}

\begin{lstlisting}
	% Plot function f(x) = 2*x^3 - x - 2
	ezplot('2*x^3-x-2',[0, 2])
	hold on
	plot([0,2],[0,0],'r')
\end{lstlisting}

我们来看一下效果:
在这里插入图片描述
比较发现只是简单的加入了如下一句代码:

\usepackage[framed,numbered,autolinebreaks,useliterate]{mcode}
  1. 段落中插入 Matlab 语句
    只需在段落或页脚编辑中插入如下语句:
\mcode{for i=1:3, disp('cool'); end;}
\footnote{Works also in footnotes: \mcodefn{for i=1:3, disp('cool'); end;}}

即使用 \mcode{}
效果如下:
在这里插入图片描述

而要实现这些需要在main.tex的目录下加一个mcode.sty文件

具体内容如下:(可以新建文件然后复制过去直接使用)记得改文件名为mcode.sty
也可以去下载:传送门https://www.mathworks.com/matlabcentral/fileexchange/8015-m-code-latex-package

%%
%%   This is file `mcode.sty'
%%
%%   It is supposed to help you easily include MATLAB source code
%%   into LaTeX document,  but have it nicely highlighted, using
%%   the great listings package.
%%
%%   PLEASE NOTE that this package does nothing but save you from
%%   figuring out some configurations  in setting up the LISTINGS
%%   package. ALL the work is done by that package!  Thus, please
%%   refer your questions to the listings package documentation.
%%
%%   Usage: You have three ways of including your MATLAB code. As
%%   environment,  as inline object and directly from an external
%%   file.
%%
%%   1) Environment:
%%
%%          \begin{lstlisting}
%%             YOUR CODE HERE
%%          \end{lstlisting}
%%
%%
%%   2) Inline object*:
%%
%%          Bla bla \mcode{CODEFRAGMENT} bla bla.
%%
%%
%%   3) Include external file (in environment form)
%%
%%          \lstinputlisting{YOUR-FILE.m}
%%
%%
%%   For your convenience this package has the following options:
%%
%%   - bw  if you intend to print the document (highlighting done
%%         via text formatting (bold, italic) and shades of gray)
%%   
%%   - numbered  if you want line numbers
%%
%%   - autolinebreaks  if you want  the package to  automatically
%%          wrap your  code.  This is buggy as it  may well break
%%          break syntax and it  doesn't work well with comments.
%%          You REALLY should wrap your code manually.
%%
%%   - useliterate   if you want  some characters / relations  in
%%          your code to be replace with something more readable.
%%          Example: ~= becomes $\neq$, >= becomes $\geq$,  delta
%%          becomes $\delta$ and so on.
%%
%%   - framed  if you want a frame  around the source code blocks
%%
%%   - final  if you have  ``gloablly'' set the draft option, the
%%         listings package will  not output the code at all.  to
%%         force it to  do so anyway,  load this package with the
%%         final option (passes the ``final'' on to listings).
%%
%%   For example, you may use \usepackage[numbered,framed]{mcode}
%%   in your document preamble.
%%   
%%   * If you want to place  some inline code in a footnote,  use
%%   \mcodefn{} instead (this will reduce the font size a bit).
%%
%%   Note:  Inside code blocks you  can escape to LaTeX text mode
%%   using §...§.  For ex. §text and some math: $x^2$§,  which is
%%   especially  useful  in comments  for putting  nicely typeset
%%   equations etc.  To get the same  colour/style as in the rest
%%   of the comment use \mcommentfont, i.e. §\mcommentfont $x^2$§
%%
%%   To change the font used,  edit the first line in the "custo-
%%   mise below" section.  And feel free to  edit other things as
%%   well.  Refer to the documentation of the listings package to
%%   see what  else you could do.  If an extra small font  is re-
%%   quired,  use  {\fontfamily{pcr}\fontsize{3}{4.6}\selectfont}
%%   in the definition of \lstbasicfont.
%%
%%   Author:
%%      Florian Knorn | florian@knorn.org | www.florian-knorn.com
%%
%%   Version history:
%%      2.7  --  Bugfixes + keywords (thanks Hildo Guillardi Jr.)
%%      2.6  --  Add support for µ, fix for math-minus problem
%%      2.5  --  Renamed internal variables (thx S. Kranenbarg!)
%%      2.4  --  Added \mcodefn{} command (thx Tony Almeida!)
%%      2.3  --  More keywords (thx Dominik Wild!)
%%      2.2  --  Bugfix (thx Willi Gerbig!)
%%      2.1  --  Finally automatic detection between end and end
%%      2.0  --  New options for line breaking and literate prog.
%%      1.8  --  Fixed typo in documentation regarding §...§
%%      1.7  --  Added MATLAB block comment syntax %{ ...... %}
%%      1.6  --  Added some infos, dealing with keyword ``end''
%%      1.5  --  Tweaked check to see wether textcomp is loaded
%%      1.4  --  Fixed misconfig (mathescape now set to false)
%%      1.3  --  Purely cosmetic (tabs replaced by spaces)
%%      1.2  --  Added \lstset{showstringspaces=false}
%%      1.1  --  Added \mcode command and [final] option
%%      1.0  --  Release


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%              D O N ' T    T O U C H    T H I S                %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\def\fileversion{2.7}
\def\filedate{2015/11/11}

\typeout{-- Package: `mcode' \fileversion\space <\filedate> --}
\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{mcode}[\filedate\space\fileversion]

% for bw-option
\newif\ifmcode@bw
\DeclareOption{bw}{\mcode@bwtrue}

% numbered option
\newif\ifmcode@numbered
\DeclareOption{numbered}{\mcode@numberedtrue}

% final option
\newif\ifmcode@final
\DeclareOption{final}{\mcode@finaltrue}

% autolinebreaks option
\newif\ifmcode@autolinebreaks
\DeclareOption{autolinebreaks}{\mcode@autolinebreakstrue}

% literate programming (replace certain characters/relations
\newif\ifmcode@useliterate
\DeclareOption{useliterate}{\mcode@useliteratetrue}

% framed option
\newif\ifmcode@framed
\DeclareOption{framed}{\mcode@framedtrue}

\DeclareOption*{% default
  \PackageWarning{mcode}{Unknown option `\CurrentOption' !}%
}
\ProcessOptions

\ifmcode@bw\typeout{ - settings optimized for printing (bw formating)}
\else\typeout{ - settings optimized for display (colour formating)}\fi
\ifmcode@numbered\typeout{ - line numbering enabled}\else\fi
\ifmcode@useliterate\typeout{ - literate programming (character replacements) enabled}\else\fi
\ifmcode@autolinebreaks\typeout{ - automatic line breaking enabled (careful, buggy!)}\else\fi
\ifmcode@framed\typeout{ - framed listings}\else\fi

% This command allows you to typeset syntax highlighted Matlab
% code ``inline''.  The font size \small seems to look best...
\newcommand{\mcode}[1]{\lstinline[basicstyle=\lstbasicfont\small]|#1|}

% Same, but for footnotes
\newcommand{\mcodefn}[1]{\lstinline[basicstyle=\lstbasicfont\footnotesize]|#1|}

% check if color command exists
\ifx\color\undefined%
  \RequirePackage{xcolor}%
\fi

% check if listings has been loaded
\ifx\lstset\undefined%
  \ifmcode@final
    \RequirePackage[final]{listings}
  \else
    \RequirePackage{listings}
  \fi
\fi

% Check if textcomp has been loaded (this package is needed for
% upright quotes '' (instead of typographic ones `´)...
\ifx\textquotesingle\undefined% 
  \RequirePackage{textcomp}%
\fi

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                C U S T O M I S E   B E L O W                  %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% ---------------------------------------------------------------------------------
% default font
\def\lstbasicfont{\fontfamily{pcr}\selectfont\footnotesize}

% ---------------------------------------------------------------------------------
% matlat languate definition
\lstdefinelanguage{matlabfloz}{%
  alsoletter={...},%
  morekeywords={%                             % keywords
		break,case,catch,classdef,continue,else,
		elseif,end,for,function,global,if,
		otherwise,parfor,persistent,
		return,spmd,switch,try,while,...},        % Use the matlab "iskeyword" command to get those
  comment=[l]\%,                              % comments
  morecomment=[l]...,                         % comments
  morecomment=[s]{\%\{}{\%\}},                % block comments
  morestring=[m]'                             % strings 
}[keywords,comments,strings]%

% ---------------------------------------------------------------------------------
% general definitions
\lstset{%
  basicstyle={\lstbasicfont},                 % set font
  showstringspaces=false,                     % do not emphasize spaces in strings
  tabsize=4,                                  % number of spaces of a TAB
  mathescape=false,escapechar=§,              % escape to latex with §...§
  upquote=true,                               % upright quotes
  aboveskip={1.5\baselineskip},               % a bit of space above listings
  columns=fixed                               % nice spacing
}

% ---------------------------------------------------------------------------------
% define colours and styles
\ifmcode@bw % use font formating and gray 'colors'
	\def\mcommentfont{\color[gray]{.75}\itshape} %comments light gray and italic
  \lstset{language=matlabfloz,                % use our version of highlighting
    keywordstyle=\bfseries,                   % keywords in bold
    commentstyle=\mcommentfont,               % comments 
    stringstyle=\color[gray]{0.5}             % strings darker gray
  }
\else% notbw => use colors : )
	\def\mcommentfont{\color[rgb]{.133,.545,.133}} %comments in green
  \lstset{language=matlabfloz,                % use our version of highlighting
    keywordstyle=\color[rgb]{0,0,1},          % keywords in blue
    commentstyle=\mcommentfont,               % comments
    stringstyle=\color[rgb]{.627,.126,.941}   % strings in purple
  } 
\fi%bw

% ---------------------------------------------------------------------------------
% automatic line breaking --- warning, this is buggy and
% doesn't break comments correctly!
\ifmcode@autolinebreaks
	\newsavebox{\lbreakdots}\sbox{\lbreakdots}{\lstbasicfont\mcommentfont...}
	\lstset{breaklines=true,breakatwhitespace=true,prebreak=\usebox{\lbreakdots}}
\fi

% ---------------------------------------------------------------------------------
% literate replacements
% the following is for replacing some matlab relations like >= or ~=
% by the corresponding LaTeX symbols, which are much easier to read ...
\ifmcode@useliterate
	\lstset{%
		literate=%
			{~}{{$\neg$}}1 %               \neg, logical not
			{<=}{{\tiny$\leq$}}1 %         \leq
			{>=}{{\tiny$\geq$}}1 %         \geq
			{~=}{{\tiny$\neq$}}1 %         \neq, not equal
			{delta}{{\tiny$\Delta$}}1 %    \Delta
			{µ}{{$\mu$}}1 %                \mu
			{(end)}{\lstbasicfont (end)}{5} % black ``end'' when indexing last vector element
			{({ }end)}{\lstbasicfont ({ }end)}{6}
			{(end{ })}{\lstbasicfont (end{ })}{6}
			{({ }end{ })}{\lstbasicfont ({ }end{ })}{7}
			{:end}{\lstbasicfont :end}{4}
			{:{ }end}{\lstbasicfont :{ }end}{5}
			{end:}{\lstbasicfont end:}{4}
			{end{ }:}{\lstbasicfont end{ }:}{5}
			{,end}{\lstbasicfont ,end}{4}
			{,{ }end}{\lstbasicfont ,{ }end}{5}
	}
\else
	\lstset{%
		literate=%
			{(end)}{\lstbasicfont (end)}{5} % black ``end'' when indexing last vector element
			{({ }end)}{\lstbasicfont ({ }end)}{6}
			{(end{ })}{\lstbasicfont (end{ })}{6}
			{({ }end{ })}{\lstbasicfont ({ }end{ })}{7}
			{:end}{\lstbasicfont :end}{4}
			{:{ }end}{\lstbasicfont :{ }end}{5}
			{end:}{\lstbasicfont end:}{4}
			{end{ }:}{\lstbasicfont end{ }:}{5}
			{,end}{\lstbasicfont ,end}{4}
			{,{ }end}{\lstbasicfont ,{ }end}{5}
			{µ}{$\mu$}1
			{~}{{\fontfamily{ptm}\selectfont\texttildelow}}1 % get a nicer tilde character
	}
\fi%literates

% ---------------------------------------------------------------------------------
% line numbering
\ifmcode@numbered% numbered option
  \lstset{%
    numbersep=3mm, numbers=left, numberstyle=\tiny, % number style
  }
\fi

\ifmcode@framed%   framed option
  \lstset{%
    frame=single,rulecolor=\color{black}            % frame
  }
  \ifmcode@numbered%
    \lstset{%
      framexleftmargin=6mm, xleftmargin=6mm         % tweak margins
    }
  \fi
\fi

% fix for ``minus'' character issue, as suggested by Stefan Karlsson, thanks!
\makeatletter 
\lst@CCPutMacro\lst@ProcessOther {"2D}{\lst@ttfamily{-{}}{-{}}} 
\@empty\z@\@empty 
\makeatother

\endinput
%% End of file `mcode.sty'.

参考链接
仅供学习之用,侵删。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/91759.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

JavaScript刷LeetCode拿offer-二叉树层序遍历篇

前言 博主最近在刷leetcode&#xff0c;做到二叉树套题的时候发现很多题的解题思路都是基于二叉树的层序遍历来完成的&#xff0c;因此写下这篇文章&#xff0c;记录一下二叉树层序遍历这件"神器"在实战的运用。 [leetcode] 102.二叉树的层序遍历 二叉树的层序遍历…

[附源码]Python计算机毕业设计高校宿舍管理系统Django(程序+LW)

该项目含有源码、文档、程序、数据库、配套开发软件、软件安装教程 项目运行 环境配置&#xff1a; Pychram社区版 python3.7.7 Mysql5.7 HBuilderXlist pipNavicat11Djangonodejs。 项目技术&#xff1a; django python Vue 等等组成&#xff0c;B/S模式 pychram管理等…

Vue渲染器(五):快速diff算法

渲染器&#xff08;五&#xff09;&#xff1a;快速diff算法 这章开始讨论第三种用于比较新旧vnode的方式&#xff1a;快速diff算法。跟它的名字一样&#xff0c;它很快。Vue3采用的就是这种算法&#xff0c;Vue2采用的是上一章中的双端diff算法。 接下来就来着重了解它的实现…

宝塔部署前后端分离项目(Vue+SpringBoot)

目录 后端部分 配置Redis 前端部分 后端部分 1 先修改自己的speingboot配置文件&#xff0c;我的是yml文件 保证宝塔上建的数据库和自己代码里&#xff0c;就是配置文件中所建的数据库的名字是一致的密码也要保持一致&#xff0c;Redis也一样&#xff0c;如果有的话 2 记录…

关注电动汽车能效水平 提高续航能力

电动汽车&#xff08;EV&#xff09;近些年发展迅猛&#xff0c;已被汽车业内普遍认为是未来汽车发展的新方向&#xff0c;但是现如今电动汽车仍然存在一些短板&#xff0c;导致其还无法替代传统燃油车。对此&#xff0c;先想到的是电动车的续航问题。其实解决电动车续航问题主…

python 插值处理一维数据 interpolate

scipy库&#xff1a; 原码&#xff1a; https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html kind可选“linear”、“nearest”、“nearest-up”、“zero”、“slinear”、“quadratic”、“cubic”、“previous”或“next”之一。 “zero…

JSP sshOA办公系统myeclipse开发oracle数据库MVC模式java编程计算机网页设计

一、源码特点 JSP sshOA办公系统是一套完善的web设计系统&#xff08;系统采用ssh框架进行设计开发&#xff09;&#xff0c;对理解JSP java编程开发语言有帮助&#xff0c;系统具有完整的源代码和数据库&#xff0c;系统主要采用B/S模式开 发。开发环境为TOMCAT7.0,Myecl…

音视频编解码流程与如何使用 FFMPEG 命令进行音视频处理

一、前言 FFMPEG 是特别强大的专门用于处理音视频的开源库。你既可以使用它的 API 对音视频进行处理&#xff0c;也可以使用它提供的工具&#xff0c;如 ffmpeg, ffplay, ffprobe&#xff0c;来编辑你的音视频文件。 本文将简要介绍一下 FFMPEG 库的基本目录结构及其功能&#…

OpenWrt 安装 WireGuard

下载 img镜像 https://downloads.openwrt.org/releases/22.03.2/targets/x86/generic/openwrt-22.03.2-x86-generic-generic-squashfs-combined-efi.img.gz解压 转化格式我的是Linux # 解压 gzip -d openwrt-22.03.2-x86-generic-generic-squashfs-combined-efi.img.gz #vmwa…

如何将数学曲线变为机器人轨迹-花式show爱心代码-turtlesim篇

第一步&#xff1a;找到曲线数学描述的网址。 阅读后了解曲线所对应的xy函数。 不要选太复杂的&#xff0c;毕竟先复现出来最重要的。 第二步&#xff0c;这个函数转为C代码。 //Lovegoal_x5.54.0*pow(sin(curve_t/200.0),3);goal_y5.5((13.0*cos(curve_t/200.0)-5.0*cos(curv…

网络工程师备考6章

6.1 OSI参考模型概述 计算机的整套理论是图灵提出来的,自此创办图灵奖(计算机类最高奖项)。科学远远比技术更重要。 OSI七层模型就是科学,就是理论,所以非常重要! 注:ISO是一个机构,OSI是一个协议:分别七层 6.2 OSI参考模型 注:在传输层中,什么是端到端,例如A,…

jsp+ssm计算机毕业设计ssm校园贫困补助系统【附源码】

项目运行 环境配置&#xff1a; Jdk1.8 Tomcat7.0 Mysql HBuilderX&#xff08;Webstorm也行&#xff09; Eclispe&#xff08;IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持&#xff09;。 项目技术&#xff1a; JSPSSM mybatis Maven等等组成&#xff0c;B/S模式 Mave…

使用vite构建vue3项目与官网构建区别

使用vite构建vue3项目 一、vue3官网文档的 https://www.javascriptc.com/vue3js/guide/installation.html#命令行工具-cli npm init vite-app cd npm installnpm run dev 二、vite官网文档的 https://cn.vitejs.dev/guide/#trying-vite-online 1 对应路径cmd 输入 npm create…

Grad-CAM简介-网络 热力图分析

论文名称&#xff1a;Grad-CAM: Visual Explanations from Deep Networks via Gradient-based Localization 论文下载地址&#xff1a;https://arxiv.org/abs/1610.02391 推荐代码&#xff08;Pytorch&#xff09;&#xff1a;https://github.com/jacobgil/pytorch-grad-cam bi…

流媒体开源服务 MediaSoup 初识

目录 前言 正文 一、简单介绍 二、关键特色 1. 超强 SFU 功能 2. Node.js 模块 3. 客户端 SDK 三、架构组成 1. 关键实例 2. 重要模块 四、发展现状 前言 最近收看了一期微软&#xff08;中国&#xff09;关于云原生、大数据、AI 领域的开源服务创新的线上圆桌论坛&…

垃圾回收算法

1.种类 垃圾回收算法通常意义上有两种&#xff1a; 引用计数式垃圾收集追踪式垃圾收集 追踪式垃圾收齐又称“间接垃圾收集”&#xff0c;现在有很多算法大都遵循了分代收集理论&#xff0c;而分代收集理论的基础&#xff0c;却是以下俩个分代假说&#xff1a; 强分代假说&am…

MyPerf4J一个高性能、无侵入的Java性能监控和统计工具,有点东西!

背景 随着所在公司的发展&#xff0c;应用服务的规模不断扩大&#xff0c;原有的垂直应用架构已无法满足产品的发展&#xff0c;几十个工程师在一个项目里并行开发不同的功能&#xff0c;开发效率不断降低。 于是公司开始全面推进服务化进程&#xff0c;把团队内的大部分工程…

软件测试之移动app测试框架有哪些?

一、适用于Android的移动app测试框架 1.Espresso 十分流行的一款谷歌开发的Android测试框架&#xff0c;具备高性能性。可以创建非常简单直接的测试&#xff0c;而不必担心app的基础架构。此外&#xff0c;它是开源的&#xff0c;这使开发人员能够自定义框架。 2.Selendroid…

DOM算法系列003-获取节点A相对于节点B 的位置

UID: 20221214170009 aliases: tags: source: cssclass: created: 2022-12-14 1. 节点位置关系 两个节点A、B之间的位置关系总共有几种&#xff1f;我们第一时间能想到的&#xff1a; 节点A在节点B之后节点A在节点B之前节点A包含节点B节点A被节点B包含 除此之外&#xff0c;…

【python绘制地图——使用folium制作地图,可解决多数问题】

Python使用folium制作地图并生成png图片 提示&#xff1a;这里可以添加系列文章的所有文章的目录&#xff0c;目录需要自己手动添加 第一章 使用folium制作地图 第二章 使用Html2Image生成png图片 第三章 使用reportlab制作pdf报告 提示&#xff1a;写完文章后&#xff0c;目录…