MATLAB 常用函数汇总大全和高级应用总结
基础应用
1. 基本数学运算函数
函数 | 功能 | 示例 |
---|---|---|
abs(x) | 绝对值 | abs(-3) → 3 |
sqrt(x) | 平方根 | sqrt(16) → 4 |
exp(x) | 指数函数 exe^xex | exp(1) → 2.7183 |
log(x) | 自然对数 | log(exp(3)) → 3 |
log10(x) | 常用对数(以 10 为底) | log10(100) → 2 |
sin(x), cos(x), tan(x) | 三角函数(弧度制) | sin(pi/2) → 1 |
asin(x), acos(x), atan(x) | 反三角函数 | asin(1) → 1.5708 |
round(x) | 四舍五入 | round(3.6) → 4 |
floor(x) | 向下取整 | floor(3.6) → 3 |
ceil(x) | 向上取整 | ceil(3.2) → 4 |
mod(a,b) | 取模 | mod(7,3) → 1 |
rem(a,b) | 余数 | rem(7,3) → 1 |
sign(x) | 符号函数(-1, 0, 1) | sign(-5) → -1 |
2. 矩阵与数组操作
函数 | 功能 | 示例 |
---|---|---|
size(A) | 返回矩阵维度 | size([1 2; 3 4]) → [2 2] |
length(A) | 向量长度 / 最大维度长度 | length([1 2 3 4]) → 4 |
numel(A) | 元素总数 | numel(eye(3)) → 9 |
reshape(A,m,n) | 改变矩阵形状 | reshape(1:6,2,3) → 2x3 矩阵 |
transpose(A) / A.' | 转置(不共轭) | [1+2i 3; 4 5]' |
ctranspose(A) / A' | 共轭转置 | [1+2i 3; 4 5]' |
diag(A) | 提取/生成对角矩阵 | diag([1 2 3]) |
triu(A) | 上三角矩阵 | triu(magic(3)) |
tril(A) | 下三角矩阵 | tril(magic(3)) |
inv(A) | 矩阵求逆 | inv([1 2; 3 4]) |
pinv(A) | 广义逆(伪逆) | pinv([1 2; 3 4]) |
det(A) | 行列式 | det([1 2; 3 4]) |
rank(A) | 矩阵秩 | rank([1 2; 2 4]) → 1 |
eig(A) | 特征值与特征向量 | [V,D] = eig([1 2; 2 1]) |
svd(A) | 奇异值分解 | [U,S,V] = svd(rand(3)) |
3. 统计与线性代数
函数 | 功能 | 示例 |
---|---|---|
mean(A) | 平均值 | mean([1 2 3]) → 2 |
median(A) | 中位数 | median([1 3 2]) → 2 |
var(A) | 方差 | var([1 2 3]) → 1 |
std(A) | 标准差 | std([1 2 3]) → 1 |
sum(A) | 求和 | sum([1 2 3]) → 6 |
prod(A) | 连乘 | prod([1 2 3]) → 6 |
max(A) | 最大值 | max([3 7 2]) → 7 |
min(A) | 最小值 | min([3 7 2]) → 2 |
corrcoef(A,B) | 相关系数 | corrcoef([1 2 3],[2 4 6]) |
4. 绘图与可视化
函数 | 功能 | 示例 |
---|---|---|
plot(x,y) | 二维折线图 | plot(0:0.1:2*pi, sin(0:0.1:2*pi)) |
scatter(x,y) | 散点图 | scatter(rand(10,1), rand(10,1)) |
bar(y) | 柱状图 | bar([1 3 2]) |
histogram(A) | 直方图 | histogram(randn(1000,1)) |
pie(A) | 饼图 | pie([2 3 4]) |
surf(X,Y,Z) | 三维曲面图 | surf(peaks) |
mesh(X,Y,Z) | 三维网格图 | mesh(peaks) |
contour(X,Y,Z) | 等高线图 | contour(peaks) |
imshow(I) | 显示图像 | imshow(imread('cameraman.tif')) |
imagesc(A) | 可视化矩阵 | imagesc(magic(5)) |
5. 文件输入输出
函数 | 功能 | 示例 |
---|---|---|
load('file.mat') | 读取 .mat 文件 | load('data.mat') |
save('file.mat','A') | 保存变量 | save('result.mat','A') |
csvread('file.csv') | 读取 CSV | csvread('data.csv') |
csvwrite('file.csv',A) | 写入 CSV | csvwrite('output.csv',A) |
xlsread('file.xlsx') | 读取 Excel | [num,text,raw] = xlsread('data.xlsx') |
xlswrite('file.xlsx',A) | 写 Excel | xlswrite('out.xlsx',rand(5)) |
fopen, fclose, fscanf, fprintf | 文本文件操作 | fid=fopen('test.txt','w'); fprintf(fid,'%f',pi); fclose(fid); |
6. 图像处理常用函数
函数 | 功能 | 示例 |
---|---|---|
imread('file') | 读入图像 | I = imread('cameraman.tif') |
imwrite(I,'file') | 保存图像 | imwrite(I,'out.png') |
rgb2gray(I) | 彩色转灰度 | Igray = rgb2gray(I) |
imresize(I, scale) | 图像缩放 | imresize(I,0.5) |
imrotate(I, angle) | 图像旋转 | imrotate(I,45) |
imcrop(I, rect) | 裁剪图像 | imcrop(I,[50 50 100 100]) |
edge(I,'canny') | 边缘检测 | BW = edge(I,'canny') |
fft2(I) | 二维傅里叶变换 | F = fft2(I) |
ifft2(F) | 逆变换 | I2 = ifft2(F) |
7. 信号处理常用函数
函数 | 功能 | 示例 |
---|---|---|
fft(x) | 快速傅里叶变换 | fft([1 2 3 4]) |
ifft(X) | 逆 FFT | ifft(fft([1 2 3 4])) |
filter(b,a,x) | IIR/FIR 滤波 | y = filter([1 -1],[1],x) |
conv(x,h) | 卷积 | conv([1 2 3],[1 1]) |
xcorr(x,y) | 互相关 | xcorr([1 2 3],[1 1]) |
spectrogram(x) | 时频分析 | spectrogram(sin(0:0.01:10)) |
8. 符号运算(Symbolic Math Toolbox)
函数 | 功能 | 示例 |
---|---|---|
syms x | 定义符号变量 | syms x y |
diff(f,x) | 符号微分 | diff(sin(x),x) → cos(x) |
int(f,x) | 不定积分 | int(x^2,x) → x^3/3 |
int(f,a,b) | 定积分 | int(x^2,0,1) → 1/3 |
limit(f,x,a) | 极限 | limit(sin(x)/x,x,0) → 1 |
solve(eq,x) | 解方程 | solve(x^2-4==0,x) → ±2 |
taylor(f,x,a,n) | 泰勒展开 | taylor(exp(x),x,0,5) |
高级应用
1.进阶数据结构与类型
-
Table / timetable / categorical
table
,readtable
,writetable
:面向列的数据表,适合异构列(数值、字符串、类别)。timetable
:带时间索引的表,方便时序数据操作(retime
,synchronize
)。categorical
:节省内存并提高分组/比较效率,适用于离散标签。
T = readtable('data.csv'); TT = table2timetable(T,'RowTimes','Time'); TT2 = retime(TT,'daily','mean');
-
Sparse 矩阵
sparse
,nnz
,spy
,用于大规模稀疏系统;线性求解优先用\
(背后自动选最优方法),或eigs
,chol
(稀疏 Cholesky)。
A = sparse(i,j,v,m,n); x = A\b; % 高效稀疏求解
-
Containers & 高级集合
containers.Map
(键值表)、datetime
/duration
、string
(比 char 更现代)、cell
/struct
。
2.数值线性代数与稳定性技巧
-
优先使用高层函数(
A\b
)而非显式inv(A)
。 -
常用稳定/高效求解器:
\
(mldivide
)、lsqminnorm
(欠定最小范数)、linsolve
(可传选项)、chol
/cholupdate
、lu
、qr
、eigs
。
-
SVD/秩相关:对病态问题用
svd
或svds
分析奇异值分布,做截断正则化(TSVD)。 -
正则化 & 数值稳定化:
Tikhonov
(添加lambda*I
)、pinv
(伪逆)、ridge
(统计工具箱)。
3. 性能优化与向量化(最影响速度的点)
-
预分配:先
zeros
,nan
,cell
,避免动态扩容。A = zeros(1,1e6); for k=1:1e6, A(k)=k; end
-
向量化替代循环:尽量用矩阵运算、逻辑索引、
bsxfun
(旧),现在优先隐式扩展(implicit expansion)。% loop -> vectorized % for i: y(i)=a(i)+b; y = a + b; % 隐式扩展 / 向量运算
-
高效索引技巧:逻辑索引、
find
,用accumarray
做分组统计替代循环。 -
减少临时变量 / 内存峰值:链式运算可能产生临时大数组,必要时分步并
clear
临时结果。 -
内存查看与管理:
whos
,memory
(Windows)查看内存分配;大数组用single
或gpuArray
(见下)减小占用。 -
JIT-friendly 代码:避免在循环中使用复杂动态结构(动态字段、增长的 cell),保持数组类型一致。
4.并行计算与 GPU 加速
-
多核并行(本地/集群)
parpool
,parfor
:并行 for;适合独立迭代任务。spmd
:分布式并行,处理分块数据或 Message Passing。parfeval
,backgroundPool
:异步执行(注意你不能让我后台执行——这里仅说明)。
parpool(4); parfor i=1:Nout(i) = heavyFunc(i); end
-
GPU 加速(需要 Parallel Computing Toolbox & GPU 支持)
gpuArray
,gather
,arrayfun
(GPU 上的 elementwise 函数),大多数线性代数/FFT/conv 支持 GPU 版本。
A_gpu = gpuArray(rand(1000)); B_gpu = A_gpu * A_gpu; B = gather(B_gpu);
-
处理大数据:
tall
arrays(惰性评估)、datastore
(分块读入 CSV/Datastore)、mapreduce
(大数据 MapReduce 风格)。ds = datastore('bigdata/*.csv'); tt = tall(ds); meanVal = mean(tt.Value); % 在本地机器/cluster 上可扩展
5.I/O、数据持久化与大文件处理
-
高效读写:
matfile
(增量读写.mat
)、memmapfile
(二进制内存映射)、datastore
/tall
。m = matfile('large.mat','Writable',true); chunk = m.A(1:1000,:); % 不会把整个文件载入内存
-
表格/文本:
readtable
/writetable
/detectImportOptions
用于自动推断与自定义列类型。 -
图像/视频:
imread
,imwrite
,VideoReader
,VideoWriter
,对大视频做分帧处理并行化。
6.绘图、可视化与发布
-
现代绘图 API:
tiledlayout
替代subplot
,uifigure
+uicontrol
用于交互式 GUI(App Designer)。 -
导出高质量图:
exportgraphics
,print
,saveas
,常配-r300
或-r600
输出高分辨率图。 -
交互与动画:
plotly
(第三方)、getframe
/movie
,animatedline
(实时时绘图)。 -
三维/体数据:
trisurf
,isosurface
,volshow
(App),pcshow
(点云)、pcread
/pcwrite
。tiledlayout(1,2); ax1 = nexttile; plot(ax1,x,y); ax2 = nexttile; imagesc(ax2,rand(100)); exportgraphics(gcf,'fig.png','Resolution',300);
7.图像/信号处理常用进阶函数
- 图像(Image Processing Toolbox):
imfilter
,imgaussfilt
,imbinarize
,imopen
/imclose
,regionprops
,bwconncomp
。 - 特征与匹配(Computer Vision Toolbox):
detectSURFFeatures
,detectHarrisFeatures
,extractFeatures
,matchFeatures
。 - 频域/滤波(Signal Processing Toolbox):
designfilt
,filtfilt
,butter
,spectrogram
,welch
。
8.调试、性能剖析与测试
-
调试工具:断点、
dbstop if error
,keyboard
,disp
/fprintf
。 -
分析性能:
profile on; ...; profile viewer
,关注 CPU hotspots 与内存分配。 -
单元测试:
matlab.unittest
框架(测试类、断言、测试套件、mock)。import matlab.unittest.TestCase classdef MyTest < TestCasemethods(Test)function testSimple(tc)tc.verifyEqual(1+1,2);endend end
-
代码覆盖率:使用
matlab.unittest.TestRunner
的覆盖率插件检查测试覆盖度。
9.代码组织与工程化
-
函数与包:使用
+package
命名空间和@class
(类)组织大型项目;addpath
,savepath
管理路径。 -
面向对象:值类(默认) vs 句柄类(继承
handle
),注意句柄类的共享语义与内存管理。 -
函数接口设计:使用
inputParser
或arguments
(新语法,R2019b 及以后)做参数检查和默认值。function out = myfun(a,b,varargin)p = inputParser;addOptional(p,'scale',1,@isnumeric);parse(p,varargin{:});s = p.Results.scale;out = a + b*s; end
-
文档与示例:在
.m
文件顶部用 help 注释,doc
自动生成帮助文档;使用 Live Script(.mlx
)写可交互教程。
10.与外部语言/工具互操作
-
MEX / C / C++:用
mex
编译 C/C++ 代码以加速关键内核(注意内存管理与类型转换)。 -
Python 集成:
py
命名空间直接调用 Python,或用pyrun
。py.numpy.array([1,2,3]);
-
Java / .NET:MATLAB 可直接调用 Java 类或编译为 Java 包。
-
部署:
MATLAB Compiler
打包为独立应用或库(注意 license 要求),Simulink Coder
生成 C 代码嵌入设备。
11.常见陷阱与实战建议
- 不要用
for
盲目替代向量化,在某些含大量复杂逻辑的情形下parfor
+ preallocation 更适合。 - 避免
eval
:维护性差且慢,用function handles
或str2func
替代。 - 注意隐式类型转换:字符串、char、cell 和 categorical 的混用会引发奇怪错误。
- 随机性可复现:
rng(seed,'twister')
固定种子。 - I/O 性能:对重复读写大数组采用
matfile
或二进制格式减少开销。 - 版本差异:
bsxfun
在旧版必须用,新版(R2016b 以后)支持隐式扩展;使用前确认目标用户的 MATLAB 版本。
12.示例:把一个循环向量化(实用示例)
原始循环:
for i=1:nC(i,:) = A(i,:) + B(i,:);
end
向量化后:
C = A + B; % 直接矩阵运算(隐式扩展或逐元素相加)
13.小结与进一步学习路径
-
优先掌握:向量化、预分配、内存管理、
parfor
、gpuArray
、table/timetable
、matfile/datastore
。 -
建议练习:
- 用
profile
找到瓶颈并向量化; - 将耗时子函数改写为 MEX 或 GPU;
- 学会用
tall
/datastore
处理超内存数据。
- 用