mcpField
M
matlab-scientific-computing

matlab-scientific-computing

github.com/jaechang-hits数据与数据库38476 次安装6 天前更新
代码仓库

关于 matlab-scientific-computing

matlab-scientific-computing 是一项数值与科学计算技能指南,示例采用也可在 GNU Octave 运行的 MATLAB 语法。面向研究者和分析人员,涵盖矩阵、模拟、信号、统计、数据处理与绘图。

主要功能

  1. 01矩阵运算与线性代数
  2. 02数值求解 ODE 和 PDE
  3. 03信号处理与滤波
  4. 04统计分析与曲线拟合
  5. 05科学绘图及数据导入导出

适用场景

  1. 01批量分析实验数据
  2. 02模拟微分方程模型
  3. 03滤波并检查测量信号
  4. 04根据结果制作出版用图表

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/jaechang-hits/sciagent-skills --skill matlab-scientific-computing

安装后在 Claude Code 中输入/matlab-scientific-computing确认已加载。

详细介绍

MATLAB/Octave — 科学计算

概述

MATLAB 是一种针对矩阵运算和科学计算优化的数值计算环境。GNU Octave 是一种免费、开源且兼容性很高的替代方案。所有代码示例均使用可在这两个平台上运行的 MATLAB 语法。

适用场景

  • 执行矩阵运算和线性代数计算(特征值、SVD、最小二乘)
  • 数值求解常微分方程和偏微分方程
  • 信号处理(FFT、滤波、频谱分析)
  • 创建二维/三维科学可视化图表和出版级图表
  • 数值优化和求根
  • 统计分析和曲线拟合
  • 批量处理实验数据文件
  • 基于 Python 的数值计算,请改用 numpy/scipy
  • 包含推断的统计建模,请改用 statsmodels

前置条件

# GNU Octave (free, open-source)
# macOS
brew install octave
# Ubuntu/Debian
sudo apt install octave

# Running scripts
octave script.m                           # Octave
matlab -nodisplay -nosplash -r "run('script.m'); exit;"  # MATLAB

注意:MATLAB 需要 MathWorks 的商业许可证。GNU Octave 免费,且大多数 MATLAB 脚本无需修改即可运行。Octave 的主要差异:支持 # 注释、++/+= 运算符;部分 MATLAB 工具箱函数不可用。

快速入门

% Load data, fit, and plot
x = linspace(0, 2*pi, 100);
y = sin(x) + 0.1 * randn(size(x));
p = polyfit(x, y, 5);
y_fit = polyval(p, x);

figure;
plot(x, y, 'bo', x, y_fit, 'r-', 'LineWidth', 2);
xlabel('x'); ylabel('y');
legend('Data', 'Polynomial fit');
title('Curve Fitting Example');
saveas(gcf, 'fit_result.png');

核心 API

1. 矩阵运算

MATLAB 的基础是矩阵和数组。

% Create matrices
A = [1 2 3; 4 5 6; 7 8 9];    % 3x3 matrix
v = linspace(0, 1, 100);       % 100 evenly spaced points
I = eye(3);                     % Identity matrix
R = rand(3, 3);                 % Uniform random
N = randn(3, 3);                % Normal random

% Operations
B = A';                  % Transpose
C = A * B;               % Matrix multiplication
D = A .* B;              % Element-wise multiplication
x = A \ [1; 2; 3];      % Solve Ax = b (preferred over inv(A)*b)
fprintf('Solution: [%.2f, %.2f, %.2f]\n', x);
% Indexing and manipulation
A = magic(5);
sub = A(1:3, 2:4);      % Submatrix (rows 1-3, cols 2-4)
row = A(2, :);           % Entire row 2
col = A(:, 3);           % Entire column 3
A(A < 5) = 0;           % Logical indexing

% Concatenation
C = [A; ones(1, 5)];    % Vertical (add row)
D = [A, zeros(5, 1)];   % Horizontal (add column)
fprintf('Size: %d x %d\n', size(C));
2. 线性代数
A = [4 1 2; 1 3 1; 2 1 5];

% Eigendecomposition
[V, D] = eig(A);           % V: eigenvectors, D: diagonal eigenvalues
fprintf('Eigenvalues: %.2f, %.2f, %.2f\n', diag(D));

% Singular value decomposition
[U, S, V] = svd(A);
fprintf('Singular values: %.2f, %.2f, %.2f\n', diag(S));

% Matrix decompositions
[L, U, P] = lu(A);         % LU with pivoting
[Q, R] = qr(A);            % QR decomposition
R_chol = chol(A);           % Cholesky (symmetric positive definite)

% Condition number and rank
fprintf('Condition number: %.2f\n', cond(A));
fprintf('Rank: %d\n', rank(A));
3. 绘图和可视化
% 2D line plots
x = 0:0.1:2*pi;
figure;
plot(x, sin(x), 'b-', 'LineWidth', 2); hold on;
plot(x, cos(x), 'r--', 'LineWidth', 2);
xlabel('x'); ylabel('y');
title('Trigonometric Functions');
legend('sin(x)', 'cos(x)');
grid on;
saveas(gcf, 'trig.png');
% 3D surface plot
[X, Y] = meshgrid(-2:0.1:2, -2:0.1:2);
Z = X.^2 + Y.^2;
figure;
surf(X, Y, Z);
colorbar; xlabel('X'); ylabel('Y'); zlabel('Z');
title('Paraboloid');
print('-dpdf', 'surface.pdf');
% Multi-panel figure
figure;
subplot(2, 2, 1); plot(x, sin(x)); title('sin');
subplot(2, 2, 2); plot(x, cos(x)); title('cos');
subplot(2, 2, 3); bar([1 3 2 5 4]); title('Bar');
subplot(2, 2, 4); histogram(randn(1000, 1), 30); title('Histogram');
saveas(gcf, 'panels.png');
4. 数据导入/导出
% CSV / tabular data
T = readtable('data.csv');
M = readmatrix('data.csv');
fprintf('Table: %d rows x %d cols\n', height(T), width(T));

% Write data
writetable(T, 'output.csv');
writematrix(M, 'output.csv');

% MAT files (MATLAB native binary)
A = rand(100, 100);
save('data.mat', 'A');          % Save variable
S = load('data.mat', 'A');     % Load specific variable

% Images
img = imread('image.png');
fprintf('Image size: %d x %d x %d\n', size(img));
imwrite(img, 'output.jpg');
5. 统计与数据分析
data = randn(1000, 1) * 5 + 50;

% Descriptive statistics
fprintf('Mean: %.2f, Std: %.2f, Median: %.2f\n', mean(data), std(data), median(data));
fprintf('Min: %.2f, Max: %.2f\n', min(data), max(data));

% Correlation and covariance
X = randn(100, 3);
R = corrcoef(X);
fprintf('Correlation matrix:\n');
disp(R);

% Linear regression (polyfit)
x = (1:50)';
y = 2.5 * x + 10 + randn(50, 1) * 5;
p = polyfit(x, y, 1);
fprintf('Slope: %.2f, Intercept: %.2f\n', p(1), p(2));

% Moving statistics
y_smooth = movmean(y, 5);
6. 微分方程
% First-order ODE: dy/dt = -2y, y(0) = 1
f = @(t, y) -2 * y;
[t, y] = ode45(f, [0 5], 1);
figure; plot(t, y, 'b-', 'LineWidth', 2);
xlabel('Time'); ylabel('y(t)');
title('Exponential Decay');
fprintf('Final value: %.4f (expected: %.4f)\n', y(end), exp(-10));
% Second-order ODE: y'' + 0.5y' + 4y = 0 (damped oscillator)
% Convert to system: y1' = y2, y2' = -0.5*y2 - 4*y1
f = @(t, y) [y(2); -0.5*y(2) - 4*y(1)];
[t, y] = ode45(f, [0 20], [1; 0]);
figure; plot(t, y(:,1), 'b-', 'LineWidth', 2);
xlabel('Time'); ylabel('Displacement');
title('Damped Oscillator');
7. 信号处理
% Generate signal with two frequencies
fs = 1000;                       % Sampling frequency
t = 0:1/fs:1-1/fs;
signal = sin(2*pi*50*t) + 0.5*sin(2*pi*120*t) + randn(size(t))*0.2;

% FFT
Y = fft(signal);
f = (0:length(Y)-1) * fs / length(Y);
figure;
plot(f(1:length(f)/2), abs(Y(1:length(Y)/2)));
xlabel('Frequency (Hz)'); ylabel('|FFT|');
title('Frequency Spectrum');
% FIR low-pass filter (keep < 80 Hz)
b = fir1(50, 80/(fs/2));          % 50th order, cutoff 80 Hz
filtered = filter(b, 1, signal);
figure;
plot(t, signal, 'b', t, filtered, 'r', 'LineWidth', 1.5);
legend('Original', 'Filtered');
title('Low-pass Filtering');
8. 函数与编程
% Anonymous functions
f = @(x) x.^2 + 2*x + 1;
fprintf('f(5) = %d\n', f(5));   % 36

% Function files (save as myfunc.m)
% function [rmse, r2] = myfunc(y_true, y_pred)
%     residuals = y_true - y_pred;
%     rmse = sqrt(mean(residuals.^2));
%     ss_res = sum(residuals.^2);
%     ss_tot = sum((y_true - mean(y_true)).^2);
%     r2 = 1 - ss_res / ss_tot;
% end

% Struct for organized data
experiment.name = 'Trial 1';
experiment.data = rand(10, 3);
experiment.params = struct('temp', 37, 'pH', 7.4);
fprintf('Experiment: %s, %d samples\n', experiment.name, size(experiment.data, 1));

核心概念

向量化

MATLAB 针对向量化运算进行了优化。尽可能避免显式循环:

% Slow (loop)
n = 1e6;
y = zeros(1, n);
tic;
for i = 1:n
    y(i) = sin(i/1000);
end
t_loop = toc;

% Fast (vectorized)
tic;
y = sin((1:n)/1000);
t_vec = toc;
fprintf('Loop: %.3fs, Vectorized: %.3fs, Speedup: %.1fx\n', t_loop, t_vec, t_loop/t_vec);
逐元素运算与矩阵运算
运算符矩阵运算逐元素运算
乘法A * BA .* B
除法A / B(右除)A ./ B
幂A ^ n(矩阵幂)A .^ n
ODE 求解器选择
求解器阶数适用场景
ode454-5默认选择。适用于大多数非刚性问题
ode232-3粗略解,每步速度更快
ode113可变高精度,计算开销较大的求值
ode15s可变刚性问题(化学动力学、电路)
ode23s2刚性问题,中等精度

常见工作流

工作流:数据分析流程
% 1. Load data
data = readtable('experiment.csv');

% 2. Clean
data = rmmissing(data);
fprintf('After cleaning: %d rows\n', height(data));

% 3. Group analysis
groups = unique(data.Category);
results = table();
for i = 1:length(groups)
    mask = strcmp(data.Category, groups{i});
    subset = data(mask, :);
    row = table(groups(i), mean(subset.Value), std(subset.Value), ...
        'VariableNames', {'Category', 'Mean', 'Std'});
    results = [results; row];
end
disp(results);

% 4. Visualize and save
figure;
bar(categorical(results.Category), results.Mean);
hold on;
errorbar(1:height(results), results.Mean, results.Std, '.k');
ylabel('Mean Value'); title('Results by Category');
saveas(gcf, 'results.png');
writetable(results, 'summary.csv');
工作流:数值模拟(热方程)
% 1D heat equation: du/dt = alpha * d2u/dx2
L = 1; N = 100; T_end = 0.5; alpha = 0.01;
dx = L / (N - 1);
dt = 0.4 * dx^2 / alpha;  % CFL condition
x = linspace(0, L, N);
nsteps = floor(T_end / dt);

% Initial condition: Gaussian pulse
u = exp(-50 * (x - 0.5).^2);

% Time stepping (explicit finite difference)
figure;
for step = 1:nsteps
    u_new = u;
    for i = 2:N-1
        u_new(i) = u(i) + alpha * dt / dx^2 * (u(i+1) - 2*u(i) + u(i-1));
    end
    u = u_new;
    if mod(step, floor(nsteps/5)) == 0
        plot(x, u, 'LineWidth', 1.5); hold on;
    end
end
xlabel('Position'); ylabel('Temperature');
title('Heat Equation Evolution');
legend(arrayfun(@(n) sprintf('t=%.2f', n*dt*floor(nsteps/5)), 1:5, 'UniformOutput', false));
saveas(gcf, 'heat_equation.png');
工作流:批量文件处理
  1. 使用 dir('data/*.csv') 列出文件
  2. 遍历文件,使用 readtable() 加载每个文件
  3. 对每个文件应用分析函数
  4. 使用 vertcat() 将结果汇总到摘要表中
  5. 使用 writetable() 导出摘要

关键参数

参数函数默认值范围效果
阶数polyfit—1–20拟合的多项式次数
tspanode45—[t0, tf]积分时间区间
'LineWidth'plot0.50.1–5图表中的线条粗细
binshistogram自动1–1000直方图的分箱数
滤波器阶数fir1—10–200FIR 滤波器阶数(越高越陡峭)
'RelTol'ode451e-31e-12–1e-1相对误差容差
'AbsTol'ode451e-61e-15–1e-1绝对误差容差

最佳实践

  1. 始终优先使用向量化,而非循环:MATLAB 的 JIT 性能不错,但对于大型数组,向量化代码的速度可快 10–100 倍。使用 bsxfun、逻辑索引和数组运算。

  2. 预分配数组:在循环中扩展数组会导致反复分配内存。

    % Bad: y = []; for i=1:n, y = [y, f(i)]; end
    % Good:
    y = zeros(1, n);
    for i = 1:n, y(i) = f(i); end
    
  3. 求解线性方程组时使用 \,而不是 inv():与 inv(A)*b 相比,A\b 数值更稳定,速度也更快。

  4. 反模式——使用 == 比较浮点数:由于浮点精度限制,应使用 abs(a - b) < tol,而不是 a == b。

  5. 发表时以矢量格式保存图形:使用 print('-dpdf', 'fig.pdf') 或 print('-dsvg', 'fig.svg'),而不是 PNG,以获得可缩放的图形。

  6. 反模式——混用从 0 和从 1 开始的索引逻辑:MATLAB 数组从 1 开始索引。从 Python/C 移植时,请调整所有索引。

  7. 格式化输出时优先使用 fprintf,而不是 disp:fprintf 可以控制数字格式;disp 只显示原始值。

常用示例

示例:使用置信区间进行曲线拟合
x = (1:20)';
y = 3 * exp(-0.2 * x) + 0.5 * randn(size(x));

% Nonlinear fit using lsqcurvefit (Optimization Toolbox)
% Or use polyfit for polynomial:
p = polyfit(x, y, 3);
y_fit = polyval(p, x);
residuals = y - y_fit;
rmse = sqrt(mean(residuals.^2));
fprintf('RMSE: %.4f\n', rmse);

figure;
plot(x, y, 'ko', x, y_fit, 'r-', 'LineWidth', 2);
xlabel('x'); ylabel('y');
title(sprintf('Polynomial Fit (RMSE = %.3f)', rmse));
saveas(gcf, 'curvefit.png');
示例:图像处理基础
img = imread('sample.png');
gray = rgb2gray(img);

% Edge detection
edges = edge(gray, 'Canny');

% Display
figure;
subplot(1, 3, 1); imshow(img); title('Original');
subplot(1, 3, 2); imshow(gray); title('Grayscale');
subplot(1, 3, 3); imshow(edges); title('Edges');
saveas(gcf, 'image_processing.png');
示例:Python 集成
% Call Python from MATLAB (requires Python on PATH)
result = py.numpy.array([1, 2, 3, 4, 5]);
py_mean = py.numpy.mean(result);
fprintf('Python numpy mean: %.1f\n', double(py_mean));

% Call MATLAB from Python (requires matlab.engine)
% import matlab.engine
% eng = matlab.engine.start_matlab()
% result = eng.sqrt(42.0)

故障排除

问题原因解决方案
Undefined function or variable函数不在路径中或名称拼写错误检查 which funcname;使用 addpath() 添加路径
* 中维度不匹配矩阵大小不兼容对逐元素运算使用 .*;检查两个操作数的 size()
ODE 求解器速度很慢刚性问题使用了非刚性求解器对刚性系统切换到 ode15s 或 ode23s
Singular matrix 警告矩阵秩亏检查 cond(A);使用 pinv()(伪逆)或进行正则化
Octave pkg 错误尚未安装软件包运行 pkg install -forge package_name; pkg load package_name
图形未保存没有活动的 figure 句柄绘图前使用 figure; 显式创建图形
Out of memory分配了大型数组使用稀疏矩阵(sparse())、分块处理或增加交换空间

相关技能

  • statsmodels-statistical-modeling — 用于统计建模并生成推断表的 Python 替代方案
  • matplotlib-scientific-plotting — Python 绘图;适用于 Python 生态系统
  • scikit-learn-machine-learning — Python 机器学习;适用于更适合使用 Python 的分类/聚类任务

参考资料

评论

支持 Markdown