矩阵与基本运算
创建矩阵和向量
MATLAB(MATrix LABoratory)将所有变量视为矩阵。向量是 1xN 或 Nx1 的矩阵。使用空格或逗号分隔行中的元素,使用分号分隔新行。zeros、ones、eye、rand 和 magic 创建常见的测试矩阵。冒号运算符 start:step:stop 生成范围(默认步长为 1)。linspace(a, b, n) 创建 n 个均匀分布的点——非常适合用作绘图坐标轴。
% row vector
v = [1 2 3 4 5];
% column vector (semicolon = new row)
c = [1; 2; 3];
% 3x3 matrix
A = [1 2 3; 4 5 6; 7 8 9];
% special matrices
Z = zeros(3); % 3x3 zeros
O = ones(2, 4); % 2x4 ones
I = eye(3); % 3x3 identity
R = rand(2, 3); % 2x3 uniform random
N = randn(4); % 4x4 normal random
M = magic(4); % 4x4 magic square
D = diag([1 2 3]); % diagonal matrix
% linear spacing
l = linspace(0, 1, 5); % [0 0.25 0.5 0.75 1]
r = 0:0.5:2; % [0 0.5 1 1.5 2]矩阵索引与切片
MATLAB 从 1 开始索引(不是从 0 开始)。冒号 : 表示'全部'——A(:,2) 是整个第二列。A(1:3, :) 选择第 1-3 行。'end' 指该维度的最后一个索引。逻辑索引(A(A > 5))非常强大——它可以提取或修改满足条件的元素。find 返回非零/真元素的索引,使用两个输出参数时可分别返回行和列。
A = magic(4); % 4x4 magic square
% single element (1-indexed!)
A(2, 3) % row 2, col 3
% entire row or column
A(1, :) % first row (all columns)
A(:, 2) % second column (all rows)
% submatrix
A(1:2, 2:4) % rows 1-2, cols 2-4
% linear indexing (column-major)
A(5) % 5th element counting down columns
% end keyword
A(end, :) % last row
A(:, end-1) % second-to-last column
% logical indexing
A(A > 10) % all elements > 10 (as vector)
A(A > 10) = 0; % set large elements to 0
% find indices
[r, c] = find(A == 16) % row and col of value 16矩阵算术运算
运算符前的点(.*)使其变为逐元素运算而非矩阵运算——这是初学者错误的头号来源。A*B 是矩阵乘法;A.*B 将对应元素相乘。反斜杠运算符(\)高效且精确地求解线性方程组(LU 分解)——始终优先使用 x = A\b 而非 inv(A)*b。撇号(')表示转置;对于复矩阵,使用 .' 进行非共轭转置。
A = [1 2; 3 4];
B = [5 6; 7 8];
% matrix operations
C = A + B; % addition
D = A - B; % subtraction
E = A * B; % matrix multiplication
F = A'; % transpose
G = A^2; % matrix power (A * A)
% element-wise operations (use the dot!)
H = A .* B; % element-wise multiply
I = A ./ B; % element-wise divide
J = A .^ 2; % element-wise power
K = 2 * A; % scalar multiply
% matrix functions
det(A) % determinant
inv(A) % inverse
pinv(A) % pseudo-inverse
rank(A) % rank
trace(A) % trace (sum of diagonal)
% solving linear systems Ax = b
b = [5; 11];
x = A \ b; % left division: solves A*x = b
x = inv(A) * b; % equivalent but slower矩阵操作
使用 [A B](空格)进行水平拼接;使用 [A; B](分号)进行垂直拼接——与行创建语法一致。reshape 按列优先填充(先向下再向右)。flipud/fliplr/rot90 重新调整矩阵方向。repmat 以网格模式平铺矩阵。将某行或某列设为 [] 可删除它。size 返回维度,length 返回最大维度,numel 返回元素总数。
A = [1 2; 3 4];
B = [5 6; 7 8];
% concatenation
C = [A B]; % horizontal: [1 2 5 6; 3 4 7 8]
D = [A; B]; % vertical: 4x4
% reshape
E = reshape(1:12, 3, 4); % 3x4 matrix from 1..12
% flip and rotate
F = flipud(A); % flip up-down
G = fliplr(A); % flip left-right
H = rot90(A); % rotate 90 degrees
% repmat (tile)
I = repmat([1 2], 2, 3); % repeat [1 2] in a 2x3 grid
% size and length
[m, n] = size(A); % m=2, n=2
len = length(A); % max dimension = 2
num = numel(A); % total elements = 4
% remove rows/cols
A(2, :) = []; % delete row 2
A(:, 1) = []; % delete column 1逐元素函数与向量化
MATLAB 的优势在于向量化——一次性对整个数组应用运算,底层运行优化的 C/Fortran 代码。sin、exp、sqrt 等自动进行逐元素运算。sum/prod/max/min 默认按列运算(维度 1);传入维度 2 则按行运算。A(:) 将矩阵展平为向量。为了性能,始终优先使用向量化运算而非 for 循环——它们可以快 10-100 倍。
% math functions operate element-wise
x = 0:0.1:2*pi;
y = sin(x); % sine of each element
z = exp(x); % exponential
w = sqrt(x); % square root
% rounding
round(3.7) % 4
floor(3.7) % 3
ceil(3.2) % 4
fix(-3.7) % -3 (toward zero)
% sums and products along dimensions
A = magic(3);
sum(A) % sum of each column (row vector)
sum(A, 2) % sum of each row (column vector)
sum(A(:)) % sum of ALL elements
prod(A) % product of each column
cumsum(A) % cumulative sum
% min, max, sort
[v, i] = max(A(:)) % max value and its index
sort(A, 'descend') % sort each column descending
% AVOID loops — vectorize!
% BAD: for i=1:1000, y(i)=sin(i); end
% GOOD:
i = 1:1000;
y = sin(i); % fast, vectorized控制流与逻辑
If / Elseif / Else
MATLAB 使用 if/elseif/else/end(注意:elseif 是一个词)。逻辑运算符:&&(标量与)、||(标量或)、&(逐元素与)、|(逐元素或)、~(非,不是 !)。字符串比较使用 strcmp/strcmpi(不区分大小写)——== 运算符只对相同长度的字符数组有效。始终用 'end' 结束代码块。
score = 85;
if score >= 90
grade = 'A';
elseif score >= 80
grade = 'B';
elseif score >= 70
grade = 'C';
else
grade = 'F';
end
disp(grade); % B
% logical operators: && (and), || (or), ~ (not)
if x > 0 && x < 10
disp('in range');
end
% compare strings with strcmp
if strcmp(name, 'Alice')
disp('hi Alice');
endFor 和 While 循环
for 遍历给定表达式的每一列(对于向量,则是每个元素)。while 在条件为真时运行。始终在循环前预分配数组(result = zeros(1,N))——在循环中增长数组会迫使每次迭代都重新分配内存,速度极慢。冒号运算符 1:5 创建 [1 2 3 4 5]。fprintf 打印格式化输出(类似 C 的 printf)。
% for loop over a range
for i = 1:5
fprintf('i = %d\n', i);
end
% iterate over a vector
v = [10 20 30];
for val = v
disp(val);
end
% nested loop over a matrix
A = zeros(3, 3);
for r = 1:3
for c = 1:3
A(r, c) = r * c;
end
end
% while loop
n = 10;
while n > 1
n = n / 2;
fprintf('%.2f\n', n);
end
% preallocate for speed (IMPORTANT!)
result = zeros(1, 1000);
for i = 1:1000
result(i) = i^2;
endSwitch 与 Break/Continue
switch 将值与 case 标签匹配——不需要 break(与 C/Java 不同)。case 可以接受元胞数组以匹配多个值。otherwise 是默认分支。break 退出最内层循环;continue 跳到下一次迭代。try/catch 优雅地处理错误;ME 是一个 MException 对象,包含 .message 和 .identifier。MATLAB 没有三元运算符——使用 if/else 或内联函数。
% switch statement
method = 'linear';
switch method
case 'linear'
disp('using linear');
case 'cubic'
disp('using cubic');
case {'nearest', 'spline'}
disp('using nearest or spline');
otherwise
disp('unknown method');
end
% break and continue
for i = 1:10
if i == 5
break % exit the loop entirely
end
if mod(i, 2) == 0
continue % skip to next iteration
end
disp(i); % prints 1 3
end
% try-catch for error handling
try
x = 1 / 0; % may error
catch ME
fprintf('Error: %s\n', ME.message);
end逻辑运算与索引
逻辑索引是 MATLAB 的杀手级特性——A(condition) 选择逻辑数组为真的元素。~= 是'不等于'(不是 !=)。& 和 | 是逐元素运算;&& 和 || 是短路运算(仅限标量,在 if 条件中优先使用)。find 返回真值的线性索引。any/all 测试是否有任何/所有元素为真,可沿指定维度进行。is* 系列函数测试类型和特殊值(NaN、Inf)。
A = [1 2 3 4 5 6 7 8 9 10];
% comparison operators
A > 5 % logical array
A == 5
A ~= 5 % not equal (NOT !=)
A >= 3 & A <= 7 % element-wise AND
A < 3 | A > 7 % element-wise OR
% logical indexing (powerful!)
A(A > 5) % [6 7 8 9 10]
A(A > 5) = 0; % set elements > 5 to 0
A(mod(A, 2) == 0) % even numbers
% find indices
idx = find(A > 5); % indices of elements > 5
[r, c] = find(A > 5); % row and col (for matrices)
% any and all
any(A > 5) % true if ANY element > 5
all(A > 0) % true if ALL elements > 0
any(A > 5, 2) % per row
% is functions
isnan(x); isinf(x); isfinite(x);
isnumeric(x); ischar(x); iscell(x);字符串与格式化
MATLAB 有两种字符串类型:字符数组('text',传统类型)和字符串标量("text",R2017+)。字符串标量在操作上更灵活。sprintf 返回格式化字符串;fprintf 打印到控制台或文件。常用格式说明符:%s(字符串)、%d(整数)、%f(浮点数)、%.2f(2 位小数)、%e(科学计数法)。strsplit/strjoin 处理分隔列表。num2str/mat2str 将数字转换为字符串。
% string creation
s1 = 'Hello'; % char array
s2 = "World"; % string scalar (R2017+)
% concatenation
greeting = [s1 ', ' s2 '!']; % char array concat
full = s1 + " " + s2; % string concat
% formatting
name = 'Alice';
age = 30;
fprintf('Name: %s, Age: %d\n', name, age);
str = sprintf('Pi is %.2f', pi); % returns string
% common string functions
upper('hello') % HELLO
lower('WORLD') % world
strlength("hello") % 5 (string)
length('hello') % 5 (char array)
strcmp('a', 'a') % true
strfind('hello', 'll') % 3 (index)
strrep('cat', 'c', 'b') % bat
strsplit('a,b,c', ',') % {'a','b','c'}
strjoin({'a','b'}, '-') % a-b
num2str(42) % '42'函数与脚本
函数定义
函数必须放在同名文件中(函数 add 放在 add.m 中),或位于脚本文件的末尾。第一行是函数声明。函数有自己的工作区(与基础工作区分开)。nargin/nargout 让你处理可选参数——nargin 计算实际输入参数个数。多个输出通过 [a, b] = func() 获取。如果调用时输出参数较少,多余的输出会被丢弃。
% function in a file named 'add.m'
function result = add(a, b)
% ADD returns the sum of a and b
result = a + b;
end
% with multiple inputs and outputs
function [mn, mx, avg] = stats(v)
mn = min(v);
mx = max(v);
avg = mean(v);
end
% calling functions
s = add(3, 4); % 7
[lo, hi, mu] = stats([1 2 3 4 5]);
% capture only first output
minimum = stats([1 2 3]); % gets mn only
% nargin and nargout (number of args)
function y = power(x, n)
if nargin < 2
n = 2; % default value
end
y = x .^ n;
end匿名函数与内联函数
匿名函数(@(args) expr)是内联定义的快速单行函数——非常适合传递给求解器(fzero、integral、ode45)而无需创建文件。它们在创建时捕获工作区变量。函数句柄(@sin)让你将内置或用户函数作为参数传递。这对数值计算至关重要:integral(@(x) f(x), a, b) 可以积分你定义的任何函数。
% anonymous function (one-liner, no file needed)
square = @(x) x .^ 2;
square(5) % 25
square([1 2 3]) % [1 4 9]
% with multiple inputs
add = @(a, b) a + b;
add(3, 4) % 7
% capture variables from workspace
c = 10;
addc = @(x) x + c;
addc(5) % 15
% function handle to built-in
f = @sin;
f(pi/2) % 1
% pass functions as arguments
result = integral(@(x) x.^2, 0, 1); % integrate x^2 from 0 to 1
result = fzero(@(x) x^2 - 2, 1); % find root near 1
% array of function handles
funs = {@sin, @cos, @tan};
funs{1}(0) % 0脚本与实时脚本
脚本是在基础工作区中运行的命令序列(不像函数有隔离的工作区)。%% 标记创建'单元格'(分区),可以用 Ctrl+Enter 独立运行——非常适合增量开发。实时脚本(.mlx)类似 Jupyter 笔记本:它们将代码、格式化文本、方程和内联绘图组合在一个交互式文档中。对于可重用代码,优先使用函数而非脚本。
% A script is just a sequence of commands in a .m file
% It shares the base workspace
% script: analyze_data.m
data = load('data.mat');
cleaned = data.values(data.values > 0);
mean_val = mean(cleaned);
fprintf('Mean: %.2f\n', mean_val);
plot(cleaned);
title('Cleaned Data');
% sections (cells) with %%
%% Initialize
x = linspace(0, 2*pi, 100);
%% Plot
plot(x, sin(x));
%% Analyze
disp(mean(sin(x)));
% Run a section: Ctrl+Enter (in editor)
% Live Scripts (.mlx): rich text, inline plots, equations嵌套函数与局部函数
脚本可以在文件末尾包含局部函数(自 R2016b 起)——它们只在该文件内可见。嵌套函数(定义在另一个函数内部)共享父函数的工作区,因此可以读取和修改其变量——对回调和累加器很有用,但可能使代码难以理解。函数文件中的局部函数是仅在该文件内可见的辅助函数。使用局部函数可以在不创建多个文件的情况下保持脚本有条理。
% local functions in a script (must be at the end)
% main_script.m
x = 1:10;
y = process(x);
disp(y);
function r = process(v)
r = normalize(scale(v)); % calls another local function
end
function s = scale(v)
s = v * 10;
end
function n = normalize(v)
n = v / max(v);
end
% nested function (inside another function)
function outer(x)
y = 0;
function inner()
y = y + x; % can access outer's variables
end
inner();
disp(y);
end变量作用域与全局变量
MATLAB 按值传递参数(修改时复制),因此函数不会意外更改调用者的变量——与 C/Python 不同。使用 global 实现真正的共享状态(在每个使用它的函数中声明),但优先使用参数传递。persistent 变量在函数调用之间保留其值(类似 C 中的 static)——对计数器、缓存或记忆化很有用。在首次调用时使用 isempty 检查来初始化 persistent 变量。避免使用全局变量,转而使用函数返回值或嵌套函数。
% base workspace variables
x = 10;
% functions have their OWN workspace
function y = myfunc()
% x is NOT accessible here
y = 5;
end
% pass by value (modifications don't affect caller)
function y = modify(v)
v = v * 2; % local copy
y = v;
end
a = 5;
b = modify(a); % b=10, a still 5
% global variables (use sparingly!)
global COUNTER
COUNTER = 0;
function increment()
global COUNTER
COUNTER = COUNTER + 1;
end
% persistent variables (like static in C)
function counter()
persistent count
if isempty(count)
count = 0;
end
count = count + 1;
disp(count);
end数据结构
元胞数组
元胞数组是 MATLAB 用于混合类型数据的容器(类似 Python 列表)。使用花括号 {} 访问元胞的内容,使用圆括号 () 获取元胞本身(对切片有用)。这个区别至关重要:c{1} 给出字符串;c(1) 给出包含字符串的元胞。元胞数组对于处理不同长度的字符串、可变大小的矩阵和不规则数据至关重要。num2cell/mat2cell 在数值数组和元胞之间转换。
% cell arrays hold mixed data types
c = {'Alice', 30, [1 2 3], magic(2)};
% access with {} (content) vs () (cell)
c{1} % 'Alice' (the string itself)
c(1) % {'Alice'} (a 1x1 cell)
c{3}(2) % 2 (second element of third cell)
% modify and append
c{2} = 31;
c{end+1} = 'new'; % append
c{5} = 'skip'; % auto-fills gaps with []
% multi-dimensional cell array
c2 = {'a', 'b'; 'c', 'd'}; % 2x2 cell
% iterate over cells
for i = 1:numel(c)
disp(c{i});
end
% convert: cell2mat, mat2cell, num2cell
nums = num2cell(1:5); % {1, 2, 3, 4, 5}结构体与表格
结构体用命名字段分组相关数据——像没有方法的对象。表格(R2013+)是 MATLAB 中类似 dataframe 的结构:面向列,具有命名的变量和行名。表格非常适合 CSV/Excel 数据。按名称(T.ages)或索引访问列。逻辑索引可用于行:T(T.age > 25, :) 筛选行。summary() 给出每列的统计信息。表格与 readtable/writetable 集成用于数据输入输出。
% struct: named fields with any data
user.name = 'Alice';
user.age = 30;
user.scores = [90 85 88];
disp(user.name); % Alice
% struct constructor
s = struct('name', 'Bob', 'age', 25, 'active', true);
% array of structs
users(1) = struct('name', 'Alice', 'age', 30);
users(2) = struct('name', 'Bob', 'age', 25);
disp(users(2).name); % Bob
% table (like a dataframe) — great for tabular data
names = {'Alice'; 'Bob'; 'Carol'};
ages = [30; 25; 28];
scores = [90; 85; 88];
T = table(names, ages, scores);
% access table columns
T.ages % column as array
T(:, 2) % column as table
T(1:2, :) % first 2 rows
T.age > 26 % logical indexing
T(T.age > 26, :) % rows where age > 26
% summary statistics
summary(T)字符串数组与字符处理
现代 MATLAB(R2017+)优先使用字符串数组("text")而非字符数组('text')。字符串数组支持向量化运算:strlength、+、split、join、contains、matches、replace 都可逐元素工作。字符数组在旧代码中仍然常见,某些函数也需要它。使用字符串数组存储文本集合;它们自然处理不同长度(不像字符数组需要填充或使用元胞)。
% string array (R2017+) — recommended for text
names = ["Alice", "Bob", "Carol"];
names(1) % "Alice"
names' % column string array
strlength(names) % [5 3 5]
% char array (legacy)
c = 'Hello World';
c(1:5) % 'Hello'
size(c) % [1 11]
% cell array of char vectors (legacy mixed-length)
old = {'Alice', 'Bob', 'Carol'};
% convert between types
s = string('hello'); % char -> string
c = char("hello"); % string -> char
cellarr = cellstr(names); % string array -> cell of char
% combine and split
full = "Alice" + " " + "Smith"; % "Alice Smith"
parts = split("a,b,c", ","); % ["a", "b", "c"]
joined = join(["a" "b" "c"], "-"); % "a-b-c"
% pattern matching
matches(names, 'A*') % logical: [true false false]
contains(names, 'li') % [true false false]
replace("hello", 'l', 'L') % "heLLo"Containers.Map 与集合
containers.Map 是 MATLAB 的键值字典(哈希映射)——适用于查找表和配置。键可以是字符串或数字。isKey 检查存在性;keys/values 检索所有键/值。集合运算(union、intersect、setdiff、setxor、ismember)适用于数值数组和字符串元胞数组。ismember 测试成员资格并返回逻辑数组——非常适合筛选。这些补充了逻辑索引用于数据操作。
% map (dictionary / hash table)
m = containers.Map;
m('name') = 'Alice';
m('age') = 30;
m('scores') = [90 85];
% access
m('name') % 'Alice'
isKey(m, 'name') % true
keys(m) % {'age', 'name', 'scores'}
values(m) % {30, 'Alice', [90 85]}
remove(m, 'age');
% create with initial values
m2 = containers.Map({'a','b','c'}, {1, 2, 3});
% set operations
A = [1 2 3 4 5];
B = [4 5 6 7 8];
union(A, B) % [1 2 3 4 5 6 7 8]
intersect(A, B) % [4 5]
setdiff(A, B) % [1 2 3]
setxor(A, B) % [1 2 3 6 7 8]
ismember(3, A) % true
ismember([1 6], A) % [true false]分类数组与日期时间
categorical 数组高效存储文本数据(作为带标签映射的整数)并支持排序——非常适合调查回复、评级或任何固定类别集合。datetime/duration(R2014+)用现代的、时区感知的日期系统取代了传统的 datenum/datestr 函数。日期算术很直观:添加 days()、hours()、minutes()。这些类型与表格和绘图集成,用于时间序列分析。
% categorical data (efficient for repeated strings)
colors = categorical({'red', 'blue', 'red', 'green', 'blue'});
categories(colors) % list of categories
summary(colors) % count per category
ord = categorical({'low','med','high'}, ...
{'low','med','high'}, 'Ordinal', true);
ord(1) < ord(2) % true (ordered)
% datetime
t = datetime('now') % current date and time
t = datetime(2024, 1, 15)
t.Format = 'yyyy-MM-dd HH:mm:ss';
% duration
d = duration(2, 30, 0); % 2 hours 30 min
d = hours(2) + minutes(30);
% date arithmetic
t2 = t + days(7); % add a week
t2 - t % duration of 7 days
% date strings and numbers
s = datestr(t, 'yyyy-mm-dd'); % to string (legacy)
n = datenum(t); % to serial number
t = datetime(n, 'ConvertFrom', 'datenum');
% generate date range
dates = datetime(2024,1,1) + days(0:6); % one week绘图与可视化
基本 2D 绘图
plot() 是核心的 2D 绘图函数。第三个参数指定颜色和样式('b-' = 蓝色实线)。hold on 让你叠加多个绘图;hold off 释放。始终标注坐标轴并添加图例。axis([xmin xmax ymin ymax]) 设置范围。saveas/print 导出图形——使用 -r300 的 print 可获得 300 DPI。gcf 获取当前图形句柄。'Location','best' 选项自动放置图例。
x = linspace(0, 2*pi, 100);
% line plot
plot(x, sin(x), 'b-', 'LineWidth', 2);
hold on;
plot(x, cos(x), 'r--', 'LineWidth', 2);
hold off;
% labels and legend
xlabel('x (radians)');
ylabel('amplitude');
title('Sine and Cosine');
legend('sin(x)', 'cos(x)', 'Location', 'best');
grid on;
% line styles: b- blue solid, r-- red dashed
% g: green dotted, m-. magenta dash-dot
% markers: o circle, * star, s square, + plus
% axis control
axis([0 2*pi -1.5 1.5]); % [xmin xmax ymin ymax]
xlim([0 2*pi]);
ylim([-1.5 1.5]);
% save figure
saveas(gcf, 'plot.png');
print('-dpng', '-r300', 'plot.png');多图与子图
subplot(r, c, n) 将图形分为 r 行 c 列的网格,并选择第 n 个单元格进行绘图。tiledlayout(R2019+)是现代替代方案——间距更清晰且有共享标题。nexttile 前进到下一个子图。yyaxis 创建具有两个 y 轴(左和右)的绘图,适用于不同比例的数据。始终先调用 figure 打开新窗口,否则会覆盖当前绘图。
% subplot(rows, cols, index)
figure;
subplot(2, 2, 1);
plot(x, sin(x));
title('Sine');
subplot(2, 2, 2);
plot(x, cos(x));
title('Cosine');
subplot(2, 2, 3);
plot(x, tan(x));
title('Tangent');
ylim([-5 5]);
subplot(2, 2, 4);
plot(x, exp(-x));
title('Decay');
% tiledlayout (newer, cleaner)
figure;
t = tiledlayout(2, 2);
nexttile; plot(x, sin(x)); title('Sine');
nexttile; plot(x, cos(x)); title('Cosine');
nexttile; plot(x, tan(x)); title('Tangent');
nexttile; plot(x, exp(-x)); title('Decay');
title(t, 'Trig Functions'); % overall title
% multiple y-axes
yyaxis left; plot(x, sin(x));
yyaxis right; plot(x, 100*cos(x));专用绘图
MATLAB 有数十种专用绘图:bar/barh(条形图)、histogram(替代 hist)、scatter(可选颜色/大小映射)、pie、area、stem、stairs、compass、feather。scatter(x, y, size, color, 'filled') 特别强大——第 4 个参数按值着色点,揭示第三维度。使用 'Normalization','pdf' 的 histogram 归一化为概率密度,便于与连续分布比较。
% bar chart
bar([1 2 3], [10 15 7]);
bar([1 2 3; 4 5 6], 'grouped'); % grouped bars
bar([1 2 3; 4 5 6], 'stacked'); % stacked bars
% histogram
data = randn(1000, 1);
histogram(data, 30); % 30 bins
histogram(data, 'Normalization', 'pdf');
% scatter plot
x = rand(100, 1);
y = 2*x + randn(100, 1)*0.1;
scatter(x, y, 50, 'filled');
% colored scatter
scatter(x, y, 50, y, 'filled'); % color by y value
colorbar;
% pie chart
pie([30 20 50], {'A', 'B', 'C'});
% area plot
area(1:5, [1 3 2 4 5]);
% stem (discrete)
stem(0:5, [1 4 9 16 25 36]);
% boxplot (requires Statistics toolbox)
boxplot(randn(100, 3));3D 绘图与曲面
plot3 绘制 3D 参数曲线。对于曲面,首先用 meshgrid 创建网格,然后计算 Z = f(X, Y)。surf 绘制填充曲面;mesh 绘制线框;contour 绘制 2D 等高线。colormap(jet、parula、hot、cool)控制颜色映射;colorbar 添加图例。shading interp 移除网格线以获得平滑渐变。view(az, el) 设置相机角度。'EdgeColor','none' 隐藏网格线以获得干净的外观。
% 3D line plot
t = 0:0.1:10*pi;
plot3(sin(t), cos(t), t);
xlabel('x'); ylabel('y'); zlabel('z');
% meshgrid for surface plots
[X, Y] = meshgrid(-2:0.1:2);
Z = X .* exp(-X.^2 - Y.^2);
% surface plots
figure;
subplot(1, 3, 1);
surf(X, Y, Z); % surface
title('surf');
subplot(1, 3, 2);
mesh(X, Y, Z); % wireframe
title('mesh');
subplot(1, 3, 3);
contour(X, Y, Z, 20); % contour lines
title('contour');
% colored surface with colorbar
figure;
surf(X, Y, Z, 'EdgeColor', 'none');
colorbar;
colormap jet;
shading interp; % smooth colors
% view angle
view(45, 30); % azimuth, elevation
axis equal;绘图自定义与导出
几乎每个视觉方面都可通过名称-值对或 set() 自定义。颜色是 0-1 范围的 RGB 三元组 [r g b]。set(gca, ...) 修改当前坐标轴(字体、比例、范围)。MATLAB 通过 'Interpreter','latex' 在标题/标签中支持 LaTeX。exportgraphics(R2020+)是现代导出函数,支持矢量和高 DPI 选项。使用图形句柄(f1、f2)管理多个窗口。annotation() 添加箭头、文本框和形状。
% customize line appearance
plot(x, y, ...
'Color', [0.2 0.6 0.8], ... % RGB 0-1
'LineWidth', 2, ...
'Marker', 'o', ...
'MarkerSize', 8, ...
'MarkerFaceColor', 'r');
% annotations
text(1, 0.5, 'important point');
annotation('arrow', [0.3 0.5], [0.3 0.5]);
% figure and axes properties
set(gcf, 'Position', [100 100 800 600]);
set(gca, 'FontSize', 14, 'FontName', 'Arial');
set(gca, 'XScale', 'log'); % log scale
% latex in labels
title('Function: \\alpha + \\beta^2', 'Interpreter', 'latex');
% export high quality
exportgraphics(gcf, 'plot.pdf', 'ContentType', 'vector');
exportgraphics(gcf, 'plot.png', 'Resolution', 300);
% legend customization
legend('show', 'Location', 'northwest', ...
'FontSize', 12, 'Box', 'off');
% multiple figures
f1 = figure; plot(x, sin(x));
f2 = figure; plot(x, cos(x));
figure(f1); % switch back to f1数据分析与统计
描述性统计
MATLAB 提供了全面的统计函数。mean/median/mode 用于集中趋势;std/var/range/iqr 用于离散程度。默认情况下,这些函数沿第一维度(列)运算。使用 'omitnan' 跳过 NaN 值(对真实世界数据很重要)。quantile/prctile 给出百分位数。统计和机器学习工具箱添加了 geomean、harmmean、zscore 和分布函数。分析前始终检查 NaN——它们会通过大多数运算传播。